> ASP.NET MVC 3: Generate unobtrusive validation when BeginForm is on the layout
> ASP.NET MVC 3 unobtrusive client-side validation with dynamic content
我有一个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.
还有其他方法可以启用客户端验证吗?
编辑
根据下面的counsellorben的回答,我设置了FormContext,现在属性正确呈现,但是验证仍然无法正常工作(如果我添加一个新行并将文本框留空,则应用程序通知的第一个是我的断点时编辑POST动作被击中).
我做了一些测试,并且肯定正在调用$.validator.unobtrusive.parse函数,parseElement函数肯定被称为表中新输入数量的正确次数,以及“info.attachValidation”行);”进一步向下解析功能肯定会受到打击.这就是我所拥有的.还在测试.
您遇到的问题是,当服务器创建新行时,不存在FormContext.必须存在FormContext才能将不显眼的验证属性添加到生成的HTML中.将以下内容添加到局部视图的顶部:if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
counsellorben
