Reputation: 34158
I have model with bool property IsMale. In view i have table with values how i can change value?
I tried this:
<td>
@if (item.IsMale == true)
{
@Html.DisplayFor(modelItem => "Male")
}
else
{
@Html.DisplayFor(modelItem => "Female")
}
</td>
But im getting error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
And in create view how i can make radio buttons >Male >Female and return it in bool?
Upvotes: 0
Views: 5103
Reputation: 14716
@Html.DisplayFor
takes a property of the model and outputs the value of that property. What you are trying to do is printing a hardcoded string. You don't need DisplayFor
for that. Just try:
<td>
@if (item.IsMale)
{
<text>Male</text>
}
else
{
<text>Female</text>
}
</td>
A better design would be if you don't make the gender a boolean value. You may want to add "Unspecified" or whatever later. If you make the gender a "first class" entity, the names "male" vs. "female" as well as the radio buttons don't have to be hardcoded:
Say you have a class called "Gender" with a property "Name". Your modelItem would then have a property "Gender" with is an object of type "Gender".
<td>@Html.DisplayFor(modelItem => modelItem.Gender.Name)</td>
and for the radios you could retrieve the whole list of available genders from your data source and put them as a RadioButtonList into the ViewModel. Then you can simply use:
@Html.RadioButtonListFor(modelItem => modelItem.AllGenders)
See also Has anyone implement RadioButtonListFor<T> for ASP.NET MVC?
Upvotes: 2
Reputation: 4359
Perhaps you could use something like this:
@Html.CheckBoxFor(model => model.IsMale)
I see that it is a radio button you want...
@Html.RadioButtonFor(model => model.IsMale, true)
@Html.RadioButtonFor(model => model.IsMale, false)
Upvotes: 1