Sunday, 7 July 2013

Html.BeginForm() vs Ajax.BeginForm() in MVC3

Html.BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax.BeginForm() creates a form that submits its values using an asynchronous ajax request. This allows a portion of the page to be update without requiring that the entire page be refreshed.

We need to understand the difference between the behaviors of both Html and Ajax forms. Ajax:
  1. Wont redirect the form even you do a RedirectAction().
  2. Will perform save , update and any modification operations asynchronously.
Html:
  1. Will redirect the form.
  2. Will perform operations both Synchronously and Asynchronously (With some extra code and care).
for better understanding We'll Create a MVC3 Project Demo.
So, for this Create a new MVC3 Project. Add a Model Class in Model Folder named 'personModel'


public class personModel
    {
        public int EID { get; set; }
        public string name { get; set; }
    }

Add Action method in HomeController Class as below described:
// for  Html.beginform() 
        public ActionResult HtmlForm()
        {
            return View();
        }

        [HttpPost]
        public ActionResult HtmlForm(personModel pm)
        {
            return Content("Hi, Your EMp ID is: "+pm.EID+" and Name is: "+pm.name);
        }
//end code for  Html.beginform() 

now, Create a View for HtmlForm Action. View Code is described below:
@model AjaxAndHtmlForm.Models.personModel
@{
    ViewBag.Title = "HtmlForm";
}
<h2>HtmlForm</h2>
<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 (Html.BeginForm("HtmlForm", "Home", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>personModel</legend>

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

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

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

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

-------------------------------------------------------------------------
now, to access the HtmlForm Action, add the below code snippet in Index.cshtml Page within Home Directory.
@Html.ActionLink("HTML Form","HtmlForm","Home")
<br />
@Html.ActionLink("Ajax Form","AjaxForm","Home")

Now, Run your Application . Output Looks Like below snapshot
Click on HTML Form Link. it'll redirect you to the HtmlForm View that you have added. Fill the EmpID and Name. Click on Create Button. see the Output.
Html.BeginForm() Refresh the Entire Page and display Output

HTML.BeginForm refresh the entire page and  redirect you to display the returned Output as HTML formet.

Now See,  Ajax.beginForm()
Ajax.beginForm Partially Update the Data on the Same Page. it does not redirect you to another Page.
for this you have to add 
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"> </script>
in the _Layout.cshtml Page.

Add Action method in HomeController Class as below described:


        public ActionResult AjaxForm()

        {
            return View();
        }

        [HttpPost]
        public ActionResult AjaxForm(personModel pm)
        {
            return Content("Hi, Your EMp ID is: " + pm.EID + " and Name is: " + pm.name);
        }

now, Create a View for AjaxForm Action (Ajaxform.cshtml) . View Code is described below:


@model AjaxAndHtmlForm.Models.personModel
@{
    ViewBag.Title = "AjaxForm";
}
<h2>AjaxForm</h2>
<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("AjaxForm", "Home", new AjaxOptions { HttpMethod="Post", UpdateTargetId="result" }))
{
    <div id="result"></div>
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>personModel</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.EID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EID)
            @Html.ValidationMessageFor(model => model.EID)
        </div>

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

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Now, Run your Application . Output Looks Like below snapshot



Click on Ajax Form Link. it'll redirect you to the AjaxForm View that you have added. Fill the EmpID and Name. Click on Create Button. see the Output.
Ajax.BeginForm() Call the AjaxForm Action and display returned Result in Target Control. here in Ajaxform  Target Control is <div id="result"></div>.
Output looks like below Snapshot:


Download the complete Demo Project: Click Me!

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. TechnoSoftwar proficient in web design and development, Dot Net development, Customized ERPs, CRMs, Web & Mobile Applications, eCommerce platforms etc.

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives