ViewModel中的验证无效

本文关键字:无效 验证 ViewModel | 更新日期: 2023-09-27 18:21:52

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

并且我有MainIndex,其中返回我的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。代码如下。

@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。。我没有任何想法,所以我想请你帮忙。顺致敬意,

ViewModel中的验证无效

我建议您这样做:

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