0

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?

3 Answers 3

2

@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?

Sign up to request clarification or add additional context in comments.

Comments

2
<td>

  @Html.Display(item.IsMale ? "Male" : "Female" )

</td>

Comments

1

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) 

1 Comment

A check box would be a very unusual way to present such a choice to the user: "[ ] I am a male person (please do not check this box if you are a female person)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.