繁体   English   中英

ViewModel中的验证不起作用

[英]Validation in ViewModel not working

我有ViewModel,其中包含一些类的属性。 下面的代码。

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


}

在这种情况下,重要属性是Patient 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; }
}

并且我有Main Index ,在其中返回我的ViewModel,因为在同一View中显示两个Model。 下面的代码

 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>

}

请注意,此表单将重定向到另一个Controller ,在该Controller中将验证数据并将其保存到数据库。 验证和保存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。我没有任何想法,所以我想向您寻求帮助。 最好的祝福。

我建议您这样做:

[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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM