Meryovi
Meryovi

Reputation: 6231

Inconsistent null attribute handling in ASP.NET MVC 4

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:

EDIT

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

Upvotes: 0

Views: 532

Answers (1)

SLaks
SLaks

Reputation: 887777

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.

Upvotes: 1

Related Questions