jQuery Validate 正在使用 MVC 分部视图 ASP.NET 但不适用于编辑器模板



我有一个编辑器模板患者配置文件视图,该视图在一个子模型中传递,子模型有 2 个字段用于 2 个输入。我正在尝试使用 jQuery 验证来验证这两个输入字段,但它不起作用。

但是,当我尝试将该确切的视图创建为部分视图时,即在共享文件夹下具有确切的患者配置文件视图,然后使用

@Html.Partial("PatientProfile", Model.PatientProfile(

然后验证有效。

Form.cshtml 视图,用于呈现患者配置文件视图

@model Test.Models.FormGroup1
@{
ViewBag.Title = "FormGroup1";
Layout = "~/Views/Shared/_ContainerLayout.cshtml";
}
@Html.Partial("PatientProfile", Model.PatientProfile)   @* Validation Works *@
@Html.EditorFor(m => m.PatientProfile)                  @* Renders but validation does not work *@

PatientProfile.chstml View

@model Test.Models.PatientProfile
<form id="PatientProfile" class="form-horizontal" action="@Url.Action("PatientProfile", "Form")" method="post" autocomplete="off">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-md-2 col-sm-2 col-form-label control-label">Firstname</label>
<div class="col-md-10 col-sm-10 validateInput">
@Html.TextBoxFor(model => model.Firstname.Value, new { @class = "form-control", placeholder = "", tabindex = "2" })
@Html.ValidationMessageFor(model => model.Firstname.Value, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="col-md-2 col-md-2 col-sm-2 col-form-label control-label">Lastname</label>
<div class="col-md-10 col-sm-10 validateInput">
@Html.TextBoxFor(model => model.Lastname.Value, new { @class = "form-control", placeholder = "", tabindex = "3" })
@Html.ValidationMessageFor(model => model.Lastname.Value, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
</form>
<script>
$(document).ready(function () {
$("#PatientProfile").validate({
onfocusout: function (element) { 
$(element).valid();
},
rules: {
"Firstname.Value": { required: true },
"Lastname.Value": { required: true },
},
errorElement: "em",
errorPlacement: function (error, element) {
error.addClass("help-block");
if (element.prop("type") === "checkbox") {
error.insertAfter(element.parent("label"));
} else {
error.insertAfter(element);
}
},
highlight: function (element, errorClass, validClass) {
$(element).parents(".validateInput").addClass("has-error").removeClass("has-success");
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".validateInput").removeClass("has-error");
},
});
});
</script>

如何让验证与 EditorFor(m => m.PatientProfile( 一起使用?我需要它与 EditorFor 一起使用,因为字段需要更新/编辑,我认为我无法使用部分视图,如果我错了,请纠正我。

如果您使用浏览器检查工具查看输入字段,您可能会发现它们的名称与您预期的名称不同。

在编辑器模板中,hold 属性设置为前缀,因此从内存中,它们将看起来像

PatientProfile.FirstName.Value

如果你想改变它,在你的编辑器模板中,你可以做

@model Test.Models.PatientProfile
@{
ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
}

这将从字段名称中删除患者配置文件

最新更新