MVC中单选按钮的验证消息

时间:2016-08-02 06:55:21

标签: asp.net-mvc validation radio-button radiobuttonfor

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

我的问题是
我有性别的单选按钮,"男性"和"女性",我该如何验证这些字段?

我的ViewModel

    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();
        }
    }

1 个答案:

答案 0 :(得分:2)

我知道它有点晚了,但它可能对其他人有所帮助。由于您使用的是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");
            }

    }

希望这有帮助。