不引人注目的验证不适用于动态添加的部分视图
我目前在动态添加内容后面临验证问题。
我有一个强类型化到模型的视图 (Order
)。该订单可以有很多项目。该模型如下所示:
public class Order
{
[Key]
[HiddenInput]
public int id { get; set; }
[Display(Name = "Order Number")]
public string number { get; set; }
[Display(Name = "Order Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime date { get; set; }
[Required(ErrorMessage = "Beneficiary is required.")]
[Display(Name = "Beneficiary")]
public int beneficiary_id { get; set; }
[Display(Name = "Beneficiary")]
public Beneficiary beneficiary { get; set; }
[Display(Name = "Items")]
public List<Item> items { get; set; }
[Display(Name = "Payment Method")]
public List<PaymentMethod> payment_methods { get; set; }
}
我输入订单信息以及该特定订单的项目。我尝试了几种动态添加内容的方法,最后选择了 史蒂文·桑德森的方式。
在我看来,我有常规的订单信息,然后是项目,我的模型看起来像这样:
@model trackmeMvc.Models.Model.Order
@{
ViewBag.Title = "Create";
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
@using (Html.BeginForm("Create", "Order", FormMethod.Post, new { @id = "create_order" }))
{
@Html.ValidationSummary(true, "Order creation was unsuccessful. Please correct the errors and try again.")
<div class="editor-label">
@Html.LabelFor(m => m.date)<req>*</req>
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.date, new { @id = "order_date" })<br />
@Html.ValidationMessageFor(m => m.date)
</div>
...
<script type="text/javascript">
$(document).ready(function () {
$("#addItem").click(function () {
var formData = $("#main_div").closest("form").serializeArray();
$.ajax({
url: "/IPO/BlankItemRow",
type: "POST",
//data: formData,
cache: false,
success: function (html) {
$("#editorRows").append(html);
//$.validator.uobtrusive.parseDynamicContent("form *");
//$("#editorRows").removeData("validator");
//$("#editorRows").removeData("unobtrusiveValidation");
//$.validator.unobtrusive.parse("#editorRows");
//$.validator.unobtrusive.parse("#create_ipo");
//$.validator.unobtrusive.parseDynamicContent($(this).first().closest("form"));
//$.validator.unobtrusive.parse($("#new_ipo_item"));
//$.validator.unobtrusive.parseElement($("#editorRows").find(".editRow:last").children().find("select"));
//$("#editorRows").find(".editRow:last").find("select").each(function () {
//alert($(this).attr("id"));
//$.validator.unobtrusive.parseElement($(this));
//$.validator.unobtrusive.parseDynamicContent($(this));
//$.validator.unobtrusive.parseDynamicContent($(this).attr("name"));
//});
//$("#editorRows").children().find(".editRows:last").find("*").each(function () {
// alert($(this).attr('id'));
//$.validator.unobtrusive.parseDynamicContent('input');
//});
//var form = $(this).closest("form").attr("id");
//$(form).removeData("validator");
//$(form).removeData("unobtrusiveValidation");
//$.validator.unobtrusive.parse(form);
}
});
return false;
});
});
</script>
这些是我尝试过的一些事情,但没有任何效果。
我从 对 ASP.Net MVC 中的动态内容应用不显眼的 jquery 验证。我尝试了所有我能想到的场景,但仍然没有成功。
我还尝试了常规解析,从表单中删除验证,然后再次应用它,但新添加的元素仍然未验证:
<div id="editorRows">
@foreach (var item in Model.items)
{
@Html.Partial("_NewItem", item)
}
</div>
...并且我的部分视图看起来像这样:
@model trackmeMvc.Models.Model.Item
@{
Layout = "";
Html.EnableClientValidation(true);
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
}
<div class="editRow">
@using (Html.BeginCollectionItem("order_items"))
{
@Html.DropDownListFor(m => m.item_id, @items, "None", new { @style = "width:205px;", @id = "ddlItems", @class="ddlItem", @name="ddlItemList" })
@Html.ValidationMessageFor(m => m.item_id)
...
}
</div>
所以发生的情况是,我有一个空项目默认情况下从控制器发送到视图,以显示一个空行。该项目已验证,但是当我单击添加项目后,无论发生什么,都会从该部分出现另一行,但我无法验证它。我尝试将验证放在部分视图中(在主表单中准备好文档之前),并且我应用了我读到的所有内容,并且结果总是相同:验证第一行,而不是其他行。我尝试了 Steven Sanderson 为此目的所做的验证 - 仍然没有运气 - 即使是部分验证,发现 在此链接 接下来的页面专门针对部分验证...
我应该做什么才能使此验证正常工作?
I am currently facing a problem with validation after dynamically adding content.
I have a view strongly typed to a model (Order
). This Order can have many items. The model looks something like the following:
public class Order
{
[Key]
[HiddenInput]
public int id { get; set; }
[Display(Name = "Order Number")]
public string number { get; set; }
[Display(Name = "Order Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime date { get; set; }
[Required(ErrorMessage = "Beneficiary is required.")]
[Display(Name = "Beneficiary")]
public int beneficiary_id { get; set; }
[Display(Name = "Beneficiary")]
public Beneficiary beneficiary { get; set; }
[Display(Name = "Items")]
public List<Item> items { get; set; }
[Display(Name = "Payment Method")]
public List<PaymentMethod> payment_methods { get; set; }
}
I enter the order information and also the items for that specific order. I tried a couple of ways to add content dynamically and finally went with Steven Sanderson's way.
In my view, I have the regular Order information and then the items, where my model looks something like this:
@model trackmeMvc.Models.Model.Order
@{
ViewBag.Title = "Create";
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
@using (Html.BeginForm("Create", "Order", FormMethod.Post, new { @id = "create_order" }))
{
@Html.ValidationSummary(true, "Order creation was unsuccessful. Please correct the errors and try again.")
<div class="editor-label">
@Html.LabelFor(m => m.date)<req>*</req>
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.date, new { @id = "order_date" })<br />
@Html.ValidationMessageFor(m => m.date)
</div>
...
<script type="text/javascript">
$(document).ready(function () {
$("#addItem").click(function () {
var formData = $("#main_div").closest("form").serializeArray();
$.ajax({
url: "/IPO/BlankItemRow",
type: "POST",
//data: formData,
cache: false,
success: function (html) {
$("#editorRows").append(html);
//$.validator.uobtrusive.parseDynamicContent("form *");
//$("#editorRows").removeData("validator");
//$("#editorRows").removeData("unobtrusiveValidation");
//$.validator.unobtrusive.parse("#editorRows");
//$.validator.unobtrusive.parse("#create_ipo");
//$.validator.unobtrusive.parseDynamicContent($(this).first().closest("form"));
//$.validator.unobtrusive.parse($("#new_ipo_item"));
//$.validator.unobtrusive.parseElement($("#editorRows").find(".editRow:last").children().find("select"));
//$("#editorRows").find(".editRow:last").find("select").each(function () {
//alert($(this).attr("id"));
//$.validator.unobtrusive.parseElement($(this));
//$.validator.unobtrusive.parseDynamicContent($(this));
//$.validator.unobtrusive.parseDynamicContent($(this).attr("name"));
//});
//$("#editorRows").children().find(".editRows:last").find("*").each(function () {
// alert($(this).attr('id'));
//$.validator.unobtrusive.parseDynamicContent('input');
//});
//var form = $(this).closest("form").attr("id");
//$(form).removeData("validator");
//$(form).removeData("unobtrusiveValidation");
//$.validator.unobtrusive.parse(form);
}
});
return false;
});
});
</script>
Those are some of the things I tried, and nothing works.
I got the parseDynamicContent
from Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC. I tried it in every scenario I could think of, but still no luck.
I also tried the regular parse, removing validation from the form then applying it again, but still the newly added elements are not validated:
<div id="editorRows">
@foreach (var item in Model.items)
{
@Html.Partial("_NewItem", item)
}
</div>
... and my partial view would look something like this:
@model trackmeMvc.Models.Model.Item
@{
Layout = "";
Html.EnableClientValidation(true);
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
}
<div class="editRow">
@using (Html.BeginCollectionItem("order_items"))
{
@Html.DropDownListFor(m => m.item_id, @items, "None", new { @style = "width:205px;", @id = "ddlItems", @class="ddlItem", @name="ddlItemList" })
@Html.ValidationMessageFor(m => m.item_id)
...
}
</div>
So what's happening is, I have one empty item sent from the controller to the view by default, to show one empty row. That item is validated, but whatever comes after when I click add item, another row appears, from that partial, but I can't get it to validate. I tried to put the validation in the partial view, (before the document ready in the main form), and everything I read I applied, and it always ends up the same: validating the first row, and not the others. I tried the validation of Steven Sanderson done for that purpose - still no luck - even the validation for partials, found at this link
and the page that follows which is specific to partial validation...
What should I do to get this validation working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我将在这里重新开始一个新答案。
在调用
$.validator.unobtrusive.parse
之前,从表单中删除原始验证器和不显眼的验证,如下所示:相同的答案已记录在案 这里。
Ok, I am going to start over with a new answer here.
Before you call
$.validator.unobtrusive.parse
, remove the original validator and unobtrusive validation from the form like so:This same answer is documented here.
对我有用的是在调用加载部分视图后重新应用验证器。就我而言,我使用的是
$.post().then()
但您可以使用 AJAX 调用的.always()
回调执行类似的操作。What worked for me was to re-apply the validator after the call to load the partial view. In my case, I'm using
$.post().then()
but you could do something similar with a.always()
callback of an AJAX call.