i have created a view like below.
<%for (var i = 0; i < Model.customerCDTO.Count();i++)
{%>
<tr>
<td style="text-align: center; width: 10%;" class="table-content-middle">
<%if (Model.customerCDTO[i].Active == true)
{%>
<%=Html.CheckBoxFor(m=>m.customerCDTO[i].Active)%>
<%}
else
{ %>
<%=Html.CheckBoxFor(m => m.customerCDTO[i].Active)%>
<%} %>
</td>
<td class="table-content-middle" align="center" style="width: 80%;">
<%=Html.DisplayTextFor(m=>m.customerCDTO[i].Name)%>
</td>
</tr>
<%} %>
the problem with the above view is that it is giving value for null for customerCDTO[i].Name
below is my view model
public class CustomerVM
{
public List<CustomerCDTO> customerCDTO { get; set; }
}
In the above view model I have created a List property. The CustomerCDTO class definition is as follows.
public class CustomerCDTO
{
public string Name { get; set; }
public bool Active { get; set; }
public bool? IsChecked { get; set; }
}
please help.
thanks
It’s giving you a
nullvalue because your form does not contain any<input>elements corresponding to theNameproperty (which you can immediately spot if you View Source). The reason for this is thatDisplayTextForis not supposed to create such elements in the first place.An almost always bad idea would be to also call
Html.HiddenFor, which does create input elements:This would solve your problem, but then the user could simply edit the values with a tool like Firebug and change the value of
Name, which you obviously do not want since otherwise you ‘d have presented an<input>element for that. (Note: I also changedDisplayTextFortoDisplayFor, which in general is the more correct way to do things).But what to do then? Well, there’s no magic solution here. If the form doesn’t contain
Namethen it will benull, but if it does containName(even hidden) then the user can change it at will. If that’s a problem, the only option is to modify your backend code to populateNamefrom your data store.