1

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

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

我的视图模型

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

1 回答 1

3

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

    }

希望这可以帮助。

于 2016-09-01T06:42:43.703 回答