ViewModel中的验证无效

时间:2014-09-15 13:35:59

标签: c# asp.net-mvc

我有ViewModel,它包含一些类的proprty。代码如下。

 public class ViewModel
{
    public Doctor VmDoctor { get; set; }     
    public Patient VmPatient { get; set; }
    public List<Visit> VmVisit { get; set; }
    public List<Hours> hours { get; set; }
    public List<Hours> hours2 { get; set; }
    public Schedule schedule { get; set; }

    public bool BlockBtn { get; set; }
    public Test test { get; set; }


}

在这种情况下,重要的属性是患者VmPatient 。这是一个由数据库模型优先生成的模型。他有验证。下面是代码。

 public partial class Patient
{
    public Patient()
    {
        this.Visits = new HashSet<Visit>();
    }

    public int PatientID { get; set; }
    [Required(ErrorMessage = "Podaj imię.")]
    public string name { get; set; }
    [Required(ErrorMessage = "Podaj nazwisko.")]
    public string surname { get; set; }
    [Required(ErrorMessage = "Podaj pesel.")]
    [RegularExpression(@"^\(?([0-9]{11})$", ErrorMessage = "Nieprawidłowy numer pesel.")]
    public string pesel { get; set; }
    [Required(ErrorMessage = "Podaj miasto.")]
    public string city { get; set; }
    [Required(ErrorMessage = "Podaj kod pocztowy.")]
    public string zipCode { get; set; }
    [Required(ErrorMessage = "Podaj e-mail.")]
    [EmailAddress(ErrorMessage = "Nieprawidłowy adres e-mail")]
    public string email { get; set; }
    [Required(ErrorMessage = "Podaj telefon komórkowy.")]
    [RegularExpression(@"^\(?([0-9]{9})$", ErrorMessage = "Nieprawidłowy numer telefonu.")]
    public string phone { get; set; }

    public virtual ICollection<Visit> Visits { get; set; }
}

我有主索引,其中返回我的ViewModel,因为在同一个视图中显示两个模型。代码

 public ActionResult Index(int id)
    {
        ViewModel _viewModle = new ViewModel();
        schedule = new Schedule();           

        if(Request.HttpMethod == "Post")
        {

            return View(_viewModle);
        }
        else
        {
            idDr = id;
            _viewModle.schedule = schedule;
            _viewModle.BlockBtn = _repository.BlockBtn(schedule);
            _viewModle.VmDoctor = db.Doctors.Find(idDr);
            _viewModle.hours = _repository.GetHours();
            foreach (var item in _viewModle.hours)
            {
                _viewModle.hours2 = _repository.GetButtonsActiv(item.hourBtn, item.count, idDr, schedule);
            }
        }
        if (_viewModle == null)
        {
            return HttpNotFound();
        }

        return View(_viewModle);
    }

在视图索引中我显示我的对象和渲染部分_FormPatient .Code如下。

@model Dentist.Models.ViewModel

<div class="container-select-doctor">
    <div class="row">
        <div class="text-left">
            <div class="row">
                <div class="content">
                            <div class="profileImage">
                                <div class="imageContener"><img style="margin:1px;" src="@Url.Content("~/Images/" + System.IO.Path.GetFileName(@Model.VmDoctor.image))" /></div>
                            </div>
                                <div class="profileInfo">
                                    <div class="profileInfoName">@Model.VmDoctor.name @Model.VmDoctor.surname</div>
                                    <div class="profileInfoSpeciality">@Model.VmDoctor.specialty</div>
                               </div>
                </div>
           </div>
      </div>
        @ViewBag.firstDay<br />
        @ViewBag.lastDay<br />
        <div class="text-middle">


            <div class="content">

                <div id="partialZone">
                      @Html.Partial("_TableSchedule")   
                </div>
            </div>
        </div>
        <div class="text-right">
            <div class="content">
                     @Html.Partial("_FormPatient")                    
            </div>
         </div>
    </div>
</div>

,最后一步是由下面的@ Html.partial.code在主索引中呈现的表单

@model Dentist.Models.ViewModel
@using (Html.BeginForm("Create","Patient"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <font color="red">@ViewBag.Pesel</font>
    <div class="form-horizontal">


        <div class="form-group">
            @Html.LabelFor(model => model.VmPatient.email, htmlAttributes: new { @class = "control-label col-md-2" }, labelText: "E-mail:")
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.VmPatient.email, new { htmlAttributes = new { @class = "form-control" } })
                @*<input class="form-control" id="email" name="email" type="text" value="">*@
                @Html.ValidationMessageFor(model => model.VmPatient.email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.VmPatient.phone, htmlAttributes: new { @class = "control-label col-md-2" }, labelText: "Telefon kom.:")
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.VmPatient.phone, new { maxlength = 9 })
                @*<input class="form-control" maxlength="9" id="phone" name="phone" type="text" value="" />*@
                @Html.ValidationMessageFor(model => model.VmPatient.phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

}

请注意此表单重定向到另一个控制器,其中数据将被验证并保存到数据库。来自FORM的数据将被验证并保存的方法。代码

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Patient pat)
    {
        ViewModel vm = new ViewModel();
        DentistEntities db = new DentistEntities();


        if (ModelState.IsValid)
        {

            db.Patients.Add(pat);
            db.SaveChanges();
        }
        return RedirectToAction("Index", "Visit", new { id = VisitController.idDr });
    }

结论如何才能获得此表单的验证!我观察到,每次modelstate.isvalid返回false ..我没有任何想法所以我想请求你的帮助。 最好的问候。

1 个答案:

答案 0 :(得分:0)

我建议你这样做:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Patient pat)
{
    ViewModel vm = new ViewModel();
    DentistEntities db = new DentistEntities();


    if (ModelState.IsValid)
    {

        db.Patients.Add(pat);
        db.SaveChanges();
    }

    vm.VmPatient = pat;
    return View(vm);    
}

再次渲染视图,但这次验证错误消息应出现在页面上(通过视图中的ValidationMessageFor()调用)。那,至少你可以看到验证失败的原因。

或者,您可以询问模型状态,例如

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        string error = error.ErrorMessage;
    }
}