在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>
Run Code Online (Sandbox Code Playgroud)
我面临的问题是在这种情况下,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="" />
Run Code Online (Sandbox Code Playgroud)
这是设计还是我在这里遗漏了什么?这附近有工作吗?
我想的选项是在ajax加载之后 - 剥离表单并注入内部内容.
Dav*_*ick 23
你假设这是设计的,你是对的.如果你检查来源,你会看到以下内容:
// 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)
Run Code Online (Sandbox Code Playgroud)
要解决这个问题,我们可以编写一个扩展方法,用于我们的局部视图:
public static class HtmlExtentions
{
public static void EnablePartialViewValidation(this HtmlHelper helper)
{
if (helper.ViewContext.FormContext == null)
{
helper.ViewContext.FormContext = new FormContext();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我们的局部视图中使用它:
@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>
Run Code Online (Sandbox Code Playgroud)
最后一步是处理我们的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.u??nobtrusive.parse($form);
})
})
});
Run Code Online (Sandbox Code Playgroud)