使用动态表单进行ASP.Net MVC 3客户端验证

时间:2023-02-01 16:37:39

I am trying to do manual validation so I can post my form via AJAX.

我正在尝试手动验证,所以我可以通过AJAX发布我的表单。

ALSO I am loading my form dynamically using $("#formHolder").load(url);

我也在使用$(“#formHolder”)动态加载我的表单.load(url);

When I load the page into the DIV it always validates as true, even though my input box is empty.

当我将页面加载到DIV时,它总是验证为true,即使我的输入框为空。

i.e call if($("#MyForm").valid()) //is always true

即调用if($(“#MyForm”)。valid())//始终为true

However If I go to the page URL directly it works ok.

但是,如果我直接转到页面URL,它可以正常工作。

So how can I initialise the Form correctly after loading it via .load(url); since it does not exist on the page when first opened

那么如何在通过.load(url)加载表单后正确初始化表单;因为它在首次打开时不存在于页面上

My Javascript is

我的Javascript是

$('.myLink').click(function () {
    var url = '/newsletter/info/'; // this loads my HTML form from another page/view at runtime
    $("#formHolder").load(url, function () {
            $("#MyForm").validate(); // I thought this line would initialise it once it loads
           }).dialog({
        modal: true,
        width:800,
        height: 600
    });
    return false;
});

3 个解决方案

#1


15  

Calling $.validator.unobtrusive.parse() manually after the form has been loaded works

表单加载后手动调用$ .validator.unobtrusive.parse()工作

I found the solution here http://btburnett.com/2011/01/mvc-3-unobtrusive-ajax-improvements.html

我在这里找到了解决方案http://btburnett.com/2011/01/mvc-3-unobtrusive-ajax-improvements.html

#2


9  

The best solution is to call $.validator.unobtrusive.parse('#frmToBeValidated'), right after your ajax load of dynamic form.

最好的解决方案是在动态表单的ajax加载之后立即调用$ .validator.unobtrusive.parse('#frmToBeValidated')。

#3


8  

Your question does not specify if you need to do anything custom to validate the form, so I would definitely go with MVC3's built in jquery unobtrusive validation:

你的问题没有说明你是否需要做任何自定义来验证表单,所以我肯定会使用MVC3的内置jquery不显眼的验证:

If this is your model:

如果这是你的型号:

public class Person
{
    [Required(ErrorMessage = "Email address required")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Please enter valid email address")]
    public string Email { get; set; }
}

this Form-code in your view will enable validation instantly with a minimum amount of settings:

您的视图中的此表单代码将使用最少量的设置立即启用验证:

@model MvcApplication12.Models.Person

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.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 (Ajax.BeginForm(new AjaxOptions())) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

If you want more functionality when the form is posted you can use AjaxOptions:

如果您希望在发布表单时获得更多功能,则可以使用AjaxOptions:

new AjaxOptions() { UpdateTargetId = "formupdate", 
                    OnSuccess = "javascript:alert('success');", 
                    OnFailure = "javascript:alert('failure');", 
                    OnComplete = "javascript:alert('complete');", 
                    OnBegin = "javascript:alert('begin');" })

This gives you full control over custom actions as the form is submitted, completed, fails or begins.

这样,您可以在表单提交,完成,失败或开始时完全控制自定义操作。

Hope this helps!

希望这可以帮助!

#1


15  

Calling $.validator.unobtrusive.parse() manually after the form has been loaded works

表单加载后手动调用$ .validator.unobtrusive.parse()工作

I found the solution here http://btburnett.com/2011/01/mvc-3-unobtrusive-ajax-improvements.html

我在这里找到了解决方案http://btburnett.com/2011/01/mvc-3-unobtrusive-ajax-improvements.html

#2


9  

The best solution is to call $.validator.unobtrusive.parse('#frmToBeValidated'), right after your ajax load of dynamic form.

最好的解决方案是在动态表单的ajax加载之后立即调用$ .validator.unobtrusive.parse('#frmToBeValidated')。

#3


8  

Your question does not specify if you need to do anything custom to validate the form, so I would definitely go with MVC3's built in jquery unobtrusive validation:

你的问题没有说明你是否需要做任何自定义来验证表单,所以我肯定会使用MVC3的内置jquery不显眼的验证:

If this is your model:

如果这是你的型号:

public class Person
{
    [Required(ErrorMessage = "Email address required")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Please enter valid email address")]
    public string Email { get; set; }
}

this Form-code in your view will enable validation instantly with a minimum amount of settings:

您的视图中的此表单代码将使用最少量的设置立即启用验证:

@model MvcApplication12.Models.Person

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.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 (Ajax.BeginForm(new AjaxOptions())) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

If you want more functionality when the form is posted you can use AjaxOptions:

如果您希望在发布表单时获得更多功能,则可以使用AjaxOptions:

new AjaxOptions() { UpdateTargetId = "formupdate", 
                    OnSuccess = "javascript:alert('success');", 
                    OnFailure = "javascript:alert('failure');", 
                    OnComplete = "javascript:alert('complete');", 
                    OnBegin = "javascript:alert('begin');" })

This gives you full control over custom actions as the form is submitted, completed, fails or begins.

这样,您可以在表单提交,完成,失败或开始时完全控制自定义操作。

Hope this helps!

希望这可以帮助!