简体   繁体   中英

MVC5 radiobutton value error

I am a bit new to MVC having begun migrating from web forms so bear with me please.

I have a radio button group for gender defined as;

<div class="form-group">
    @Html.LabelFor(m => m.Gender, new { @class = "col-xs-3 control-label" })
    <div class="col-xs-5">
        <div class="radio">
            <label>
                @Html.RadioButtonFor(m => m.Gender, new { @class = "form-control", value= Gender.Male})<span>Male</span>
                @*<input type="radio" name="gender" value="male"/> Male*@
            </label>
        </div>
        <div class="radio">
            <label>
                @Html.RadioButtonFor(m => m.Gender, new { @class = "form-control", value = Gender.Female }) <span>Female</span >
                @*<input type="radio" name="gender" value="female"/> Female*@
            </label>
        </div>
    </div>
</div>

Where Gender is an enum defined in another project, but the viewmodel class uses that enum.

 [Required]
 [Display(Name = "Gender")]
 public DomainClasses.Enums.Gender Gender { get; set; }

No matter what I seem to try to get this right I get the following validation error.

The value '{ class = form-control, value = Male }' is not valid for Gender.

UPDATE:

The original look prior to submitting this was

在此输入图像描述

But upon changing to the suggested methods, why is the look now this?

在此输入图像描述

Look at this image

在此输入图像描述

This image shows that, there is no overload for accepting second parameter as Html Attributes ,So you need to write like this:

<div class="form-group">
    @Html.LabelFor(m => m.Gender, new { @class = "col-xs-3 control-label" })
    <div class="col-xs-5">
        <div class="radio">
            <label>
                @Html.RadioButtonFor(m => m.Gender, Gender.Male , new { @class = "form-control" })<span>Male</span>
                @*<input type="radio" name="gender" value="male"/> Male*@
            </label>
        </div>
        <div class="radio">
            <label>
                @Html.RadioButtonFor(m => m.Gender, Gender.Female,  new { @class = "form-control" }) <span>Female</span >
                @*<input type="radio" name="gender" value="female"/> Female*@
            </label>
        </div>
    </div>
</div>

In this overload, you are passing the second parameter as the value for the RadioButton

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM