0

I have been trying to handle optional HTML required and readonly attributes in ASP.NET MVC 4. For my surprise, I found out that null attributes in HTML helpers are rendered as empty strings while they are removed completely in Razor (desired behavior).

For example, this code:

  @{ string disabled = null; string @readonly = null; }

  @Html.TextBox("t1", "Value", new { disabled, @readonly })
  <input type="text" name="t2" value="Value" disabled="@disabled" readonly="@(@readonly)" />

Renders:

  <input disabled="" id="t1" name="Txt1" readonly="" type="text" value="Value" />
  <input type="text" name="t2" value="Value" />

Basically what I want to know is:

  • What is the reason behind these two different behaviors?
  • Is there a way to get the same result using Html.TexBox without writing any custom code?

EDIT

This is not possible without writing a custom Html Helper, but there's a feature request for this on CodePlex.

1 Answer 1

1

The Html.TextBox() behavior comes from code in System.Web.Mvc.Html that transforms a RouteValueDictionary of attributes into actual HTML. (I believe that code is in TagBuilder)

The raw HTML tag behavior comes from a feature in the Razor v2 language parser that removes attributes in Razor markup that resolve to null at runtime.

3
  • Yeah, but still... one will expect a consistent handling of these cases throughout the platform. Is there a way to mimic similar behavior in Html.Helpers?
    – Meryovi
    Commented May 21, 2013 at 17:16
  • @Meryovi: Not that I know of (without modifying source). You can open a feature request or pull request at aspnetwebstack.codeplex.com
    – SLaks
    Commented May 21, 2013 at 17:23
  • I just found there is already a feature request there, thanks!
    – Meryovi
    Commented May 21, 2013 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.