如何在扩展的标识模型中返回radiobutton选择的值

时间:2016-04-30 21:26:38

标签: c# asp.net-mvc radiobuttonfor

我是ASP.net MVC的新手。我现在被困住了。我扩展了身份模型,以包括生物数据,如firstName,LastName,Gender等。

我希望将性别呈现为单选按钮,我能够毫无错误地运行应用程序,但它不会提交注册。我将性别从文本框更改为单选按钮后,此问题就开始了。这是我的代码。

我的部分模型:

    [Display(Name = "Middle Name")]
    [MaxLength(25)]
    public string MiddleName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [MaxLength(25)]
    public string LastName { get; set; }

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

我的控制器:

 public async Task<ActionResult> Register(RegisterViewModel model)
    {
    if (ModelState.IsValid)
        {


            var member = new MemberInformation
            {
                Id =
                    Guid.NewGuid().ToString() + DateTime.Now.Year +             DateTime.Now.Month + DateTime.Now.Day +
                    DateTime.Now.Hour,
                FirstName = model.FirstName,
                LastName = model.LastName,
                MiddleName = model.MiddleName,
                Gender = model.Gender,
                ContactAddress = model.ContactAddress,
                MarialStatus = model.MarialStatus,
                Occupation = model.Occupation,
                MobilePhone = model.MobilePhone,
                RegistrationDate = DateTime.Now,
         }

我的观点:

    <div class="form-group">
    @Html.LabelFor(m => m.Gender, new {@class = "col-md-2 control-label",})
    <div class="col-md-10">
        @Html.LabelFor(m => m.Gender, "Male")
        @Html.RadioButtonFor(Model => Model.Gender,  "Male") 
        @Html.LabelFor(m => m.Gender, "Female")
        @Html.RadioButtonFor(m => m.Gender,  "Female")
      </div>
     </div>

2 个答案:

答案 0 :(得分:0)

我怀疑你的Model => Model.Gender表达式引起了一些混淆,因为模型已经意味着该范围内的东西。

LabelFor在使用这种方式时也很奇怪,使用html标签来简化事情

    <label>@Html.RadioButtonFor(m => m.Gender, "Male")Male</label>
    <label>@Html.RadioButtonFor(m => m.Gender, "Female")Female</label>

答案 1 :(得分:0)

当您使用Html.RadioButtonFor两次相同的模型属性时,它会创建两个具有相同ID的控件。由于回发只关心名称而不是ID,因此您需要覆盖ID,如下所示:

@Html.RadioButtonFor(m => m.Gender, "Male", new {id = "GenderMale"})
@Html.RadioButtonFor(m => m.Gender, "Female", new { id = "GenderFemale" }) 

这会创建映射到Gender但使用不同ID的radiobuttons。

注意 - 您应该包含new { id = "Whatever" }位,否则它将再次重复ID。