客户端验证的MVC 3.0动态生成的表单元素 [英] client side validating dynamically generated form elements in mvc 3.0

查看:181
本文介绍了客户端验证的MVC 3.0动态生成的表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读了很多有关如何在MVC 3.0验证动态生成的内容,例如一个<一个href=\"https://xhalent.word$p$pss.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/#wpl-likebox\"相对=nofollow> xhalent 写
,但我无法理解如何在我的code使用它。我的意思是它不为动态生成的表单元素的工作。
这里是我的模型类:

 公共类Person
{
    [需要]
    公共字符串名称{;组; }    [需要]
    公共字符串电话{搞定;组; }    公众的IList&LT;地址&gt;地址{获取;设置;}    公众人物()
    {
        地址=新的List&LT;地址&gt;()
                            {
                                新地址(){街=1},新地址(){街=2}
                            };
    }
}公共类地址
{
    [必需(的ErrorMessage =错误)]
    公共字符串街{搞定;组; }
}

这其中的形式开始的视图中显示:

 &LT; SCRIPT SRC =&LT;%:Url.Content(〜/脚本/ jQuery的-1.5.1.min.js)%&gt;中类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;
&LT; SCRIPT SRC =&LT;%:Url.Content(〜/脚本/ jquery.validate.min.js)%&gt;中类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;
&LT; SCRIPT SRC =&LT;%:Url.Content(〜/脚本/ jquery.validate.unobtrusive.min.js)%&gt;中
    类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;&LT;使用%(Html.BeginForm())
       {%GT;
    &LT;%:Html.ValidationSummary(真)%GT;
    &LT;&字段集GT;
        &LT;传奇&GT;与人LT; /传说&GT;
        &LT;%:Html.EditorForModel()%GT;
            &LT; D​​IV CLASS =电话号码&GT;
                &LT;%
           的foreach(在Model.Addresses VAR项)
       {            %GT;
            &LT;%Html.RenderPartial(EditorTemplates /地址,项目);%GT;
            &LT;%}%GT;
        &LT; / DIV&GT;    &LT; D​​IV的风格=填充:10px的0像素10px的0像素&GT;
        &LT;一个ID =增加手机的href =JavaScript的:无效(0);&gt;添加另一个&LT; / A&GT;
    &LT; / DIV&GT;
    &LT;输入类型=提交值=创建/&GT;
&LT; /字段集&GT;
&LT;%}%GT;
&LT; / DIV&GT;

  $()。就绪(函数(){
             $(#加手机)。点击(函数(){
                 $阿贾克斯({
                     网址:'&LT;%:Url.Action(GetNewAddress)%&GT;,
                     成功:功能(数据){
                         (电话号码)。$追加(数据);
                    }
                });
            });
        });

这是地址的局部视图:

 &LT; D​​IV的风格=填充:为5px 0像素为5px 0像素NAME =editorRowID =editorRow&GT;
        &所述;%:Html.LabelFor(M =&GT; m.Street)%GT;
        &所述;%:Html.EditorFor(M =&GT; m.Street)%GT;
        &所述;%:Html.ValidationMessageFor(M =&GT; m.Street)%GT;
    &LT; / DIV&GT;


解决方案

首先,如果你的局部视图,在顶部添加此

 &LT;%
 如果(Html.ViewContext.FormContext == NULL)
    {
        Html.ViewContext.FormContext =新FormContext();
    }
%GT;

这应该添加不显眼的数据val- *验证属性生成的内容。而在阿贾克斯下载你的成功的功能,插入<一个href=\"http://stackoverflow.com/questions/6812779/mvc-3-razor-load-partial-with-validation/6824686#6824686\">this在结束

  $()。就绪(函数(){
             $(#加手机)。点击(函数(){
                 $阿贾克斯({
                     网址:'&LT;%:Url.Action(GetNewAddress)%&GT;,
                     成功:功能(数据){
                         (电话号码)。$追加(数据);                         $(形式)removeData(验证);
                         $(形式)removeData(unobtrusiveValidation);
                         $ .validator.unobtrusive.parse(形式);                    }
                });
            });
        });

这时候它会自动解析下载的内容和应用验证它

我看了看你的项目,发现动态验证的原因不能正常工作。实际上你已经得到了在那里比验证更多的问题。首先,用于呈现地址的方法是不正确的。你产生这样的话,所有的输入具有相同的ID和名称值。这就是为什么验证器无法动态地添加内容和previous之一之间区分的原因,认为所有的输入是相同的,根据第一街验证所有街道。而且,如果你张贴的内容来创建服务器,asp.net的MVC模型绑定不可能绑定街道的阵列 - 出于同样的原因,为什么验证器不能工作。看看这个文章正确的新一代客户端上列表内容。和更高,动态注射,您可以更改控制器code像

 公众的ActionResult GetNewAddress(字符串ID)
        {
            ViewData.TemplateInfo.HtmlField preFIX =的String.Format([{0}],身份证);
            返回视图(EditorTemplates /地址,新的地址());
        }

从客户端传递正确的ID是你的:)。

另外,你没有正确使用EditorTemplates,他们是为了与 Html.DisplayFor()中使用,你不应该手动指定他们的名字。了解他们更多的,是有许多文章出现在网络上

I have read a lot about how to validate dynamically generated content in mvc 3.0 such as the one xhalent has written , But I cant understand how to use it in my code. I mean it does not work for dynamically generated form elements. Here is my Model classes:

 public class Person
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Phone { get; set; }

    public IList<Address> Addresses{get;set;}

    public Person()
    {
        Addresses = new List<Address>()
                            {
                                new Address(){Street="1"},new Address(){Street="2"}
                            };
    }


}

public class Address
{
    [Required(ErrorMessage="Error")]
    public string Street { get; set; }
}

And this the view in which the form is begin displayed:

<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js") %>" type="text/javascript"></script>
<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>

<% using (Html.BeginForm())
       { %>
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>Person</legend>
        <%: Html.EditorForModel() %>
            <div class="phone-numbers">
                <%
           foreach (var item in Model.Addresses)
       {

            %>
            <%Html.RenderPartial("EditorTemplates/Addresses", item);%>
            <%} %>
        </div>

    <div style="padding: 10px 0px 10px 0px">
        <a id="add-phone" href="javascript:void(0);">Add another</a>
    </div>
    <input type="submit" value="Create" />
</fieldset>
<% } %>
</div>

  $().ready(function () {
             $("#add-phone").click(function () {
                 $.ajax({
                     url: '<%: Url.Action("GetNewAddress") %>',
                     success: function (data) {
                         $(".phone-numbers").append(data);                   
                    }
                });
            });
        });

And this is the partial view for Address:

<div style="padding: 5px 0px 5px 0px" name="editorRow" id="editorRow">
        <%: Html.LabelFor(m => m.Street) %>
        <%: Html.EditorFor(m => m.Street)%>
        <%:Html.ValidationMessageFor(m=>m.Street) %>
    </div>

解决方案

First, if your partial view, add this at the top

<%
 if (Html.ViewContext.FormContext == null)
    {
        Html.ViewContext.FormContext = new FormContext();
    }
%>

This should add unobtrusive data-val-* validation attributes to generated content. And in your success function of ajax downloading, insert this at the end

 $().ready(function () {
             $("#add-phone").click(function () {
                 $.ajax({
                     url: '<%: Url.Action("GetNewAddress") %>',
                     success: function (data) {
                         $(".phone-numbers").append(data);      

                         $("form").removeData("validator");
                         $("form").removeData("unobtrusiveValidation");
                         $.validator.unobtrusive.parse("form"); 

                    }
                });
            });
        });

This time it should automatically parse the downloaded content and apply validations to it

I took a look at your project and found the reason of dynamic validation not working. Practically you've got more problems in there than the validation. First, the technique you use for rendering addresses is not correct. That way, all the inputs you generate have the same id and name values. That's the reason why validator cannot distinguish between dynamically added content and previous one, it thinks all the inputs are the same and validates all streets according to first street. And moreover, if you posted that content to create on server, asp.net mvc model binder could not have binded the array of streets - for the same reason why validator cannot work. Take a look at this article for proper generation of list contents on client side. And for later, dynamic injection, you can change the controller code like

public ActionResult GetNewAddress(string id)
        {
            ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("[{0}]", id);
            return View("EditorTemplates/Addresses", new Address());
        }

Passing correct id from client side is up to you :).

Also, you do not use EditorTemplates correctly, they are meant to be used with Html.DisplayFor(), and you should not have to specify their name by hand. Read about them more, there're dozens of articles there on the web

这篇关于客户端验证的MVC 3.0动态生成的表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆