ASP.NET MVC TextBoxFor helper rendering empty when null
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 = "postsD开发者_开发技巧ropDown" })%>
<% 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).
If Model
is null
, then trying to access Model.PostCode.postname
will throw a NullReferenceException, so I don't think you'll be able to fix it in TextBoxFor. You could try doing something like Model != null && Model.PostCode != null ? Model.PostCode.postname : null
but it's pretty nasty :-(
精彩评论