ASP.NET MVC TextBoxFor helper rendering empty when null
- by mare
I noticed that TextBoxFor helper renders empty if there is no model, like for instance when I have a CreateEdit ViewUserControl. When in Edit view fields are filled in, when in Create fields are empty but still rendered.
The problem is TextBoxFor does not accept different Id for its name (the same as LabelFor and others, but for LabelFor I have custom Html helpers).
So in some case we still have to use regular Html.TextBox helper. The problem is if I write this
<%=Html.TextBox("postname", Model.PostCode.postname, new { @class = "postsDropDown" })%>
an error occurs in Create view (obviously).
So I have to do this:
<% if (Model != null) %>
<%=Html.TextBox("postname", Model.PostCode.postname, new { @class = "postsDropDown" })%>
<% else %>
<%=Html.TextBox("postname", null, new { @class = "postsDropDown" })%>
Now that is something which I don't like anymore (the IF's).
Is this the only way to do it? I know I could extend TextBoxFor helpers also but seems like so much trouble. In the end we will come to extending all of the "For" helpers but I think this should be done by ASP.NET MVC team already (built-in).