gpt4 book ai didi

c# - EditorFor 在没有 BeginForm 的情况下不呈现数据验证属性

转载 作者:可可西里 更新时间:2023-11-01 03:07:39 25 4
gpt4 key购买 nike

在 MVC 应用程序中,我想动态呈现表单的某些部分(类似于 Controller 端的 PartialView)

在部分 View 中,我没有 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 之后 - 剥离表单并注入(inject)内部内容。

最佳答案

您假设这是设计使然,这是正确的。如果你检查 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)

为了解决这个问题,我们可以编写一个扩展方法用于我们的分部 View :

public static class HtmlExtentions
{
public static void EnablePartialViewValidation(this HtmlHelper helper)
{
if (helper.ViewContext.FormContext == null)
{
helper.ViewContext.FormContext = new FormContext();
}
}
}

然后在我们的部分 View 中使用它:

@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.u‌​nobtrusive.parse($form);
})
})
});

关于c# - EditorFor 在没有 BeginForm 的情况下不呈现数据验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com