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.