2016-08-02 65 views
1

目前我正在创建在线表单,所以我在验证单选按钮字段时遇到了问题。我设法为我的所有文本框创建验证消息,但似乎为单选按钮创建验证消息与为文本框创建验证方式不同?
MVC中单选按钮的验证消息

我的问题是
我有性别单选按钮,“男”和“女”,我应该如何验证这些领域?

我的视图模型

public class PersonalValidator 
{ 
    public int personalInfoId { get; set; } 

    [Required(ErrorMessage="Gender is required")] 
    public string gender { get; set; } 

    public string occupation { get; set; } 
    public Nullable<int> maritalId { get; set; } 
    public Nullable<int> registrationId { get; set; } 
    public Nullable<int> eduInfoId { get; set; } 
    public Nullable<int> monthlyId { get; set; } 
} 

我的剃须刀

 <tr> 
     <td> Gender</td> 
     <td colspan="2"> 
      @Html.RadioButtonFor(model => model.personalValid.gender, "Male") Male 
      @Html.ValidationMessageFor(model => model.personalValid.gender) 

      @Html.RadioButtonFor(model => model.personalValid.gender, "Female") Female 
      @Html.ValidationMessageFor(model => model.personalValid.gender) 
     </td> 
<tr> 

我的控制器

  [HttpPost] 
    public ActionResult TestValidation(RegisterInfoPA viewmodel) 
    { 
     using (var database = new TMXEntities()) 
     { 
      if(ModelState.IsValid) 
      { 
       var personalVM = viewmodel.personalValid;     

        //save personal info 
        personalInfo personalDB = new personalInfo(); 

        personalDB.gender = personalVM.gender;          
        personalDB.occupation = personalVM.occupation; 
        personalDB.maritalId = personalVM.maritalId; 
        personalDB.eduInfoId = personalVM.eduInfoId; 
        personalDB.monthlyId = personalVM.eduInfoId; 

        db.personalInfoes.Add(personalDB); 
        db.SaveChanges(); 

        return RedirectToAction("SuccessfullyCreated"); 

      } 

      return View(); 
     } 
    } 
+0

你需要验证什么?这两个单选按钮最初是否都关闭,并且您想检查是否已选择了一个? –

+2

是的,这两个单选按钮都没有被选中,所以当用户想要提交表单时,验证消息会出现,要求用户选择一个。用户不能不选。 – user3431310

+1

你得到的错误是什么? – user3643092

回答

1

我知道这有点晚了,但它可能会帮助其他人。由于您使用的是viewmodel,我认为最简单和最好的解决方案是使用AddModelError

在控制器

[HttpPost] 
public ActionResult TestValidation(RegisterInfoPA viewmodel) 
{ 
    using (var database = new TMXEntities()) 
    { 
     //VALIDATE FIRST 
     MainValidation(viewmodel) 

     //Proceed to process data 
     -----------codes------------------   
    } 
} 

    public void MainValidation(RegisterInfoPA validationData) 
    { 
      if (validationData.personalValid.gender == null) 
      { 
       ModelState.AddModelError("gender", "Please select gender"); 
      } 

    } 

希望这有助于。