不显眼的验证不适用于动态添加的局部视图 [英] Unobtrusive validation not working on dynamically-added partial view

查看:22
本文介绍了不显眼的验证不适用于动态添加的局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在动态添加内容后面临验证问题.

我有一个强类型化到模型的视图 (Order).这个订单可以有很多项目.该模型如下所示:

公共类订单{[钥匙][隐藏输入]公共 int id { 获取;放;}[显示(名称=订单号")]公共字符串编号 { 获取;放;}[显示(名称=订单日期")][数据类型(数据类型.日期)][DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]公共日期时间日期{获取;放;}[必需(ErrorMessage =需要受益人.")][显示(姓名=受益人")]公共 int beneficiary_id { 获取;放;}[显示(姓名=受益人")]公共受益人受益人{得到;放;}[显示(名称=项目")]公共列表<项目>项目{得到;放;}[显示(名称=付款方式")]公共列表<PaymentMethod>支付方法{得到;放;}}

我输入订单信息以及该特定订单的商品.我尝试了几种动态添加内容的方法,最后选择了 Steven Sanderson 的方式.

在我看来,我有常规的订单信息,然后是商品,我的模型看起来像这样:

@model trackmeMvc.Models.Model.Order@{ViewBag.Title = "创建";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, "订单创建失败.请更正错误并重试.")<div class="editor-label">@Html.LabelFor(m => m.date)*

<div class="editor-field">@Html.TextBoxFor(m => m.date, new { @id = "order_date" })
@Html.ValidationMessageFor(m => m.date)

...

这些是我尝试过的一些方法,但没有任何效果.

我从 parseDynamicContent="noreferrer">对 ASP.Net MVC 中的动态内容应用不显眼的 jquery 验证.我在我能想到的所有场景中都尝试了它,但仍然没有运气.

我也尝试了常规解析,从表单中删除验证然后再次应用它,但仍然没有验证新添加的元素:

@foreach(Model.items 中的 var 项目){@Html.Partial("_NewItem", item)}

...我的部分视图看起来像这样:

@model trackmeMvc.Models.Model.Item@{布局 = "";Html.EnableClientValidation(true);如果(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)...}

所以发生的事情是,默认情况下我有一个从控制器发送到视图的空项目,以显示一个空行.该项目已验证,但是当我单击添加项目后,会出现另一行,来自该部分,但我无法对其进行验证.我尝试将验证放在部分视图中(在主表单中准备好文档之前),我阅读的所有内容都应用了,结果总是相同:验证第一行,而不是其他行.我尝试了为此目的对 Steven Sanderson 进行的验证 - 仍然没有运气 - 即使是对部分的验证,发现 在这个链接以及随后特定于部分验证的页面...

我应该怎么做才能使此验证工作?

解决方案

好的,我将在这里重新开始一个新的答案.

在调用 $.validator.unobtrusive.parse 之前,从表单中删除原始验证器和非侵入式验证,如下所示:

var form = $("#main_div").closest("form");form.removeData('验证器');form.removeData('unobtrusiveValidation');$.validator.unobtrusive.parse(form);

此处记录了相同的答案.

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?

解决方案

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:

var form = $("#main_div").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);

This same answer is documented here.

这篇关于不显眼的验证不适用于动态添加的局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆