2016-08-02 64 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"); 
      } 

    } 

希望這有助於。