-1

我正在开发一个动态表单,用户可以在其中单击一个按钮,然后使用 jQuery 模板插件将一组新的控件添加到表单中。下面的代码:

@using (Html.BeginForm("Index2", "Home", FormMethod.Post, new { id = "EditForm" }))
{ 
@Html.ValidationSummary(false)

@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title)

<p>
    <input type="button" name="Add Author", value="Add Author" />
</p>

<div id="myElements">
@for (int i = 0; i < @Model.Authors.Count; i++)
{
    <div class="myElement">
        @Html.LabelFor(m => m.Authors[i].Id)  
        @Html.TextBoxFor(m => m.Authors[i].Id)
    </div>
    <div class="myElement">
        @Html.LabelFor(m => m.Authors[i].Name)  
        @Html.TextBoxFor(m => m.Authors[i].Name)
    </div>
    <br style="clear:both;" />
}
</div>

<br />
<input type="submit" name="Submit" value="Submit" />
}

<script id="AuthorTemplate" type="text/x-jquery-tmpl">
<div class="myElement">
    <input 
            data-val="true" 
            data-val-number="The field Author Id must be a number." 
            data-val-required="Author Id is required!" id="Authors_${value}__Id" 
            name="Authors[${value}].Id" 
            type="text" value="" class="valid" />
</div>
<div class="myElement">
    <input 
            data-val="true" 
            data-val-required="Author Name is required!" 
            id="Authors_${value}__Name" 
            name="Authors[${value}].Name" 
            type="text" value="" />
</div>
<br style="clear:both;" />
</script>

<script type="text/javascript">
$(document).ready(function () {
    $('input[name="Add Author"]').click(function (evt) {
        evt.preventDefault();
        $('#AuthorTemplate').tmpl({ value: $('input[name^="Authors"]').length / 2 }).appendTo('#myElements');

// Re-register unobtrusive validation
    $.validator.unobtrusive.parse('#myElements');
    });
});
</script>

该脚本工作正常,但是,尽管我重新初始化了不显眼的验证,但表单并未验证新添加的值。

有任何想法吗?

谢谢

4

2 回答 2

0

我认为你需要改变

$.validator.unobtrusive.parse('#myElements');

$.validator.unobtrusive.parse('.myElements');
于 2012-05-02T20:40:09.180 回答
0

其实,正确的做法是:

$.validator.unobtrusive.parse('#myElements');

然而,以上还不够。我必须使用以下插件来确保 jQuery Validation 插件现在知道新的规则/消息:

http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/

祝你好运,

于 2012-05-05T15:05:17.773 回答