Using Ajax.BeginForm with ASP.NET MVC 3 Razor

后端 未结 8 1029
面向向阳花
面向向阳花 2020-11-22 01:23

Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist?

This is an elusive topic f

8条回答
  •  自闭症患者
    2020-11-22 01:44

    I got Darin's solution working eventually but made a few mistakes first which resulted in a problem similar to David (in the comments below Darin's solution) where the result was posting to a new page.

    Because I had to do something with the form after the method returned, I stored it for later use:

    var form = $(this);
    

    However, this variable did not have the "action" or "method" properties which are used in the ajax call.

    $(document).on("submit", "form", function (event) {
        var form = $(this);
    
        if (form.valid()) {
            $.ajax({
                url: form.action, // Not available to 'form' variable
                type: form.method,  // Not available to 'form' variable
                data: form.serialize(),
                success: function (html) {
                    // Do something with the returned html.
                }
            });
        }
    
        event.preventDefault();
    });
    

    Instead you need to use the "this" variable:

    $.ajax({
        url: this.action, 
        type: this.method,
        data: $(this).serialize(),
        success: function (html) {
            // Do something with the returned html.
        }
    });
    

提交回复
热议问题