简体   繁体   English

MVC5 radiobutton值错误

[英]MVC5 radiobutton value error

I am a bit new to MVC having begun migrating from web forms so bear with me please. 我对MVC开始从网络表单迁移有点新,所以请耐心等待。

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. Gender是另一个项目中定义的枚举,但viewmodel类使用该枚举。

 [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. 值'{class = form-control,value = Male}'对于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: 这个图像显示,接受第二个参数作为Html属性没有重载 ,所以你需要这样写:

<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 在此重载中,您将第二个参数作为RadioButton传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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