Tuesday, April 17, 2012

ASP.Net MVC3 Ajax form submission using JQuery Ajax

This is a continuation for my previous article
http://mvc3only.blogspot.in/2012/04/aspnet-mvc3-ajax-form-submission-simple.html

where we learnt how to submit form using Asp.net mvc Ajax Beginform.

This post is for people who want to submit their form using JQuery Ajax options
Now using the same code as mentioned in ASP.Net MVC3 Ajax form submission simple example article with some modifications in the "testCreate.cshmtl" view we can submit the form using JQuery Ajax as follows.

Use the same code mentioned in the above and make some modification's in testCreate.cshmtl as follows
Views: 
~/Home/testCreate.cshtml



@model MvcApplication1.Models.testModel1
@{
    ViewBag.Title = "testCreate";
}


<script type="text/javascript">


    $(document).ready(
    function () {


        $('#frmTestCreate').live('submit', function (e) {
            e.preventDefault();
            $('#btnSubmit').attr('disabled', 'disabled');
            $('#loading').show();
            $.ajax(
            {
                cache: false,
                async: true,
                type: "POST",
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function (data) {
                    $('#result').empty();
                    $('#result').html(data);
                },
                complete: function () {
                    $('#loading').hide();
                    $('#btnSubmit').removeAttr('disabled');
                }
            }
            );
        }
        );
    }
    );


</script>


<h2>testCreate</h2>
<div id="loading" style="display:none; font-size:large; font-weight:bold">....Updating....</div>


@using (Html.BeginForm("testCreate", "Home", FormMethod.Post, new { id = "frmTestCreate" }))
{
    <table>
        <tr>
            <td>
                First Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                Last Name:
            </td>
            <td>
                @Html.TextBoxFor(m => m.LastName)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="btnSubmit" type="submit" value="Submit" />
            </td>
        </tr>
    </table>
}


<div id="result" style="color: Green;"></div>


This modification will make form submitted via JQuery Ajax. That's it we are done.


Feel free to comment..

3 comments: