Tuesday, April 17, 2012

ASP.Net MVC3 Ajax form submission using Ajax.BeginForm simple example

Hey MVC3 begginer's


Here is a simple example of using asp.net mvc3 Ajax.BeginForm to submit forms with out regular post backs. In order to understand the following stuff you need to have basic knowledge of creating basic MVC3 application.


Controller: HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers// change name spaces as required
{
    public class HomeController : Controller
    {
        //Action Method to display testCreate view
        public ActionResult testCreate()
        {
            var model = new MvcApplication1.Models.testModel1();
            return View(model);
        }

        //Action method that handles the testCreate form submission
        [HttpPost]
        public PartialViewResult testCreate(MvcApplication1.Models.testModel1 testModel)
        {
            System.Threading.Thread.Sleep(5000);// you can do your updating stuff here
            if (ReferenceEquals(testModel.FirstName, null))
                testModel.FirstName = string.Empty;
            if (ReferenceEquals(testModel.LastName, null))
                testModel.LastName = string.Empty;
            return PartialView("testPartial", testModel);
        }
    }
}

Model: testModel1.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    //Model created to bind data to testCreate view
    public class testModel1
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Views: 
~/Home/testCreate.cshtml



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

<script type="text/javascript">
    //Method that will be on begin of Ajax request, here we are displaying some text to user while update is    //going on
    function onBegin() {
        $('#loading').show();
    }

    //Method that will be called once ajax request was done and we will hide the loading text
    function onComplate() {
        $('#loading').hide();
    }

</script>

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

@using(Ajax.BeginForm("testCreate","Home",new AjaxOptions{ HttpMethod="POST", UpdateTargetId = "result", OnBegin = "onBegin()", OnComplete = "onComplate()" }))
{
    <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 type="submit" value="Submit" />
            </td>
        </tr>
    </table>
}

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


~/Home/testPartial.cshtml -> partial we will display after form submission



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

<h2>testPartial</h2>

<table>
        <tr>
            <td>
                First Name:
            </td>
            <td>
                @Html.DisplayFor(m => m.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                Last Name:
            </td>
            <td>
                @Html.DisplayFor(m => m.LastName)
            </td>
        </tr>
    </table>

~/Shared/_Layout.cshtml



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>

TestCreate Page:


TestCreate Page After entering data:


TestCreate Page After submitting:


TestCreate Page After submit:


Note: don't miss the reference to "jquery.unobtrusive-ajax.min.js" in your application.


That's it go through the above code use them as mentioned and you are ready to submit your forms just like that.


Feel free to comment..


Happy ???



14 comments:

  1. I did everything in this article but It is not work

    ReplyDelete
    Replies
    1. Hi elvin sorry for the late reply
      check if u did include all the references, mention if you are able to see any errors

      Delete
    2. I did include all the references. but page reload (refresh) when click on submit.

      Delete
    3. Use browser developer tools, you can find script errors if any

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Nice and beneficial share. it is very helpful for me to learn and endure regularly.. thanks for distributing your precious learning and time. please continue updating.

    AWS Training in HRBR Layout
    AWS Training in Kalyan Nagar
    Best AWS Training Institute in kalyan Nagar Bangalore

    ReplyDelete