在MVC应用程序中,我想动态渲染表单的某些部分(就像控制器端的PartialView一样)
在局部视图中,我没有Html.BeginForm(),因为已经呈现了表单标记。
@model Introduction.Models.Human
<div>
@Html.EditorFor(model => model.MarriageInformation.SpouseDetails)
<div class="editor-label">
@Html.LabelFor(model => model.MarriageInformation.DOM)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MarriageInformation.DOM)
@Html.ValidationMessageFor(model => model.MarriageInformation.DOM)
</div>
</div>
我面临的问题是在这种情况下,EditorFor不会返回所有data-val- *属性。
<div>
<div class="editor-label">
<label for="MarriageInformation_SpouseDetails_Name">Name</label>
</div>
<div class="editor-field"><input class="text-box single-line" id="MarriageInformation_SpouseDetails_Name" name="MarriageInformation.SpouseDetails.Name" type="text" value="" />
这是设计还是我在这里遗漏了什么?这附近有工作吗?
我想的选项是在ajax加载之后 - 剥离表单并注入内部内容。
答案 0 :(得分:23)
你认为这是设计的,这是正确的。如果您查看source,则会看到以下内容:
// Only render attributes if unobtrusive client-side validation is enabled, and then only if we've
// never rendered validation for a field with this name in this form. Also, if there's no form context,
// then we can't render the attributes (we'd have no <form> to attach them to).
public IDictionary<string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)
要解决此问题,我们可以编写一个扩展方法,以便在我们的局部视图中使用:
public static class HtmlExtentions
{
public static void EnablePartialViewValidation(this HtmlHelper helper)
{
if (helper.ViewContext.FormContext == null)
{
helper.ViewContext.FormContext = new FormContext();
}
}
}
然后在我们的局部视图中使用它:
@model Introduction.Models.Human
@{ Html.EnablePartialViewValidation(); }
<div>
@Html.EditorFor(model => model.MarriageInformation.SpouseDetails)
<div class="editor-label">
@Html.LabelFor(model => model.MarriageInformation.DOM)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MarriageInformation.DOM)
@Html.ValidationMessageFor(model => model.MarriageInformation.DOM)
</div>
</div>
最后一步是处理我们的ajax回调中的新验证属性:
$(function () {
$('button').click(function (e) {
e.preventDefault();
$.get('@Url.Action("AddSpouse")', function (resp) {
var $form = $('form');
$form.append(resp);
$form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($form);
})
})
});
答案 1 :(得分:2)
如果您希望数据验证标记存在,则需要位于FormContext
。因此,如果您动态生成表单的一部分,则需要在局部视图中包含以下行:
@{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
然后,您需要确保每次添加/删除项目时动态重新绑定不引人注意的验证:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");