相关问题:
我有一个 ASP.NET MVC 视图呈现用户可以添加到的项目集合:-
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MySite.Models.Parent>" %>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<%: Html.HiddenFor(model => model.Id) %>
<table>
<thead>
<tr>
...
<th>Value</th>
</tr>
</thead>
<tbody>
<% foreach (var child in Model.Children)
{
Html.RenderPartial("ChildRow", child );
} %>
</tbody>
</table>
<p>
<input type="submit" value="Save" />
<%= Html.ActionLink<MyController>(x => x.ChildRow(), "Add another...", new { @class = "addRow" }) %>
</p>
<% } %>
“ChildRow”部分如下:-
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MySite.Models.Child>" %>
<tr class="editor-row">
<td>
<% Html.EnableClientValidation(true);
using (Html.BeginCollectionItem("Children")) { %>
<%: Html.HiddenFor(model => model.Id)%>
</td>
<td>
<%: Html.EditorFor(model => model.Value)%>
<%: Html.ValidationMessageFor(model => model.Value)%>
<% } %>
</td>
</tr>
我正在使用 jQuery 来获取代表行的部分:-
$("a.addRow").live("click", function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$(this).parents("form:first").children("table:first tbody:last").append(html);
$.validator.unobtrusive.parse("form");
}
});
return false;
});
我遇到的问题是客户端验证不适用于 jQuery 添加的行。正如您从我的脚本中看到的那样,我在 ajax 调用之后在表单上运行验证器。据我环顾四周,问题在于 Html.BeginForm() 调用不在 ajax 部分上,因此验证属性没有被添加到输入元素中。即,如果我在添加一行后查看标记:-
页面加载时存在的输入如下所示:-
<input name="Children[0a197c09-470c-4ab4-9eef-2bcc5f0df805].Value"
class="text-box single-line" id="Children_0a197c09-470c-4ab4-9eef-2bcc5f0df805__Value"
type="text" data-val-required="The Value field is required." data-val="true" value="Test"/>
通过 ajax 添加的输入如下所示:-
<input name="Children[aa5a21b2-90bc-4e06-aadc-1f2032a121aa].Value"
class="text-box single-line" id="Children_aa5a21b2-90bc-4e06-aadc-1f2032a121aa__Value"
type="text" value=""/>
显然,由于表单的性质,我无法将 Html.BeginForm 调用移动到我的局部视图上。由于页面是通过 ajax 加载的,所以我也不能破解我部分的 FormContext。
还有另一种方法可以启用客户端验证吗?
编辑
根据下面的辅导员本的回答,我设置了 FormContext,现在属性可以正确呈现,但是验证仍然无法正常工作(如果我添加新行并将文本框留空,应用程序首先会注意到我的断点在编辑 POST 操作被击中)。
我做了一些测试,肯定会调用 $.validator.unobtrusive.parse 函数,对于表中的新输入数量,肯定会调用parseElement 函数正确的次数,并且行“info.attachValidation( );" 再往下,解析功能肯定会被击中。这就是我所知道的。还在测试。