2016-04-30 43 views
-1

我是ASP.net MVC的新手。我现在被困住了。我扩展了身份模型,以包括名字,姓氏,性别等生物数据。我如何在扩展模式内返回单选按钮模式

我想要将性别呈现为单选按钮,我可以运行应用程序而没有任何错误,但不会提交注册。在我将文本框中的性别更改为单选按钮后,此问题就开始了。这是我的代码。我的模型的

部分:

[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> 
+0

您显示的代码将正常工作并正确绑定(尽管标签不会用作标签,并且因为重复的“id”属性而导致无效的html)。如果它没有绑定,那么它由于其他代码你没有给我们显示 –

回答

0

我怀疑你的Model => Model.Gender表达会引起一些混乱,因为模型已经意味着什么在那个范围内。采用这种方式时,使用HTML标签,当您使用Html.RadioButtonFor相同的模型属性两次它将创建两个控件使用相同的ID把事情简单化

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

LabelFor亦奇。作为回传只在乎名,而不是ID,则需要覆盖的ID,如下图所示:

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

这将创建一个映射到性别单选按钮,但有不同的ID。

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

+0

不管你使用RadioButton()或RadioButtonFor()(强类型的RadioButtonFor()总是首选) –

+0

谢谢 - 更新的答案反映 – Erresen

+0

你编辑是好的,并加入'id'是很好的做法,但这不解决OP的问题,为什么它没有约束:) –