简体   繁体   中英

ASP.Net MVC 3 client side validation with a dynamic form

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

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

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

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

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

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

My Javascript is

$('.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;
});

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

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

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

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:

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:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM