POST Data In ASP.NET MVC Without Page Refresh

Posting data to the server without whole post back or we can say without page refresh is very important to save the server resources and make application faster. In ASP.NET MVC there are lot of options to achieve this without writing lots of custom code.

Many forum post I read, one common question was the difference between Html.BeginForm and Ajax.BeginForm when both are doing whole page refresh while posting data to the server and also seen lots of misleading answers, so by considering above requirement I decided to write this article. So let us see step by step .
Step 1: Create an MVC application.
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK
Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named EmpModel and right the following lines of code as.

EmpModel.cs
using System.ComponentModel.DataAnnotations;  
  
namespace AjaxBeginFormwithMVC.Models  
{  
    public class EmpModel  
    {  
  
        [Required]  
        public string Name { get; set; }  
        [Required]  
        public string City { get; set; }  
        [Required]  
        public string Address { get; set; }  
    }  
} 
Step 3: Add Home controller controller.

Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting controller template, click on add button then the following window appears,



Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as:

HomeController.cs
using AjaxBeginFormwithMVC.Models;  
using System.Web.Mvc;  
  
namespace AjaxBeginFormwithMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Home  
        [HttpGet]  
        public ActionResult EmployeeMaster()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult EmployeeMaster(EmpModel obj)  
        {  
            ViewBag.Records = "Name : " + obj.Name + " City:  " + obj.City + " Addreess: " + obj.Address;  
            return PartialView("EmployeeMaster");  
        }  
    }  
}  
In the above code, we have added EmployeeMaster Action result method and it returns the partial view named EmployeeMaster with input parameters value.

Step 4:
Add View,

Add strongly typed view named EmployeeMaster from EmpModel class: 
 

After clicking on add button the view generated .

Step 5:
Add Reference of jquery.unobtrusive-ajax

To work Ajax.BeginForm functionality properly we need to add the reference of jquery.unobtrusive-ajax library, there are many ways to add the reference of jQuery library into our project. The following are some methods,
  • Using NuGet package manager, you can install library and reference into the project.
Right click on created MVC project and find Nuget Package manager option,

Now the following window will appear and search for the jQuery unobtrusive ajax as,

 

Choose appropriate version and click on Install button. It will install jQuery UI library to your project and library script file get added into the script folder of the created project which you can add reference into the project,
  • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  • Download library using NuGet and reference into the project.
The library will be look like as follows after adding it in script folder.

 
To work Ajax.BeginForm functionality properly don't forget to add the reference of the following jQuery library as,
<script src="~/Scripts/jquery-1.10.2.js"></script>  
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>  
After adding necessary code, files and logic the EmployeeMaster.cshtml code will look like the following,
@model AjaxBeginFormwithMVC.Models.EmpModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
<script src="~/Scripts/jquery-1.10.2.js"></script>  
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>  
<div id="divEmp">  
  
  
    @using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))  
    {  
        @Html.AntiForgeryToken()  
  
        <div class="form-horizontal">  
  
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
                </div>  
            </div>  
  
            <div class="form-group">  
                @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
                </div>  
            </div>  
  
            <div class="form-group">  
                @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
                </div>  
            </div>  
  
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="Save" class="btn btn-primary" />  
                </div>  
            </div>  
            <hr />  
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-12 text-success">  
                   @ViewBag.Records  
                </div>  
            </div>  
  
        </div>  
    }  
</div>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Now run the application and click on save button without entering text in textbox, it will fire the validation as in the following,
 
From preceding example it is clear that validation also get fired. Now enter the proper details and click on save button, it will pass data to the controller asynchronously without whole page refresh as,
 
From all the above examples, how to post data to controller without Page refresh in ASP.NET MVC using Ajax.BeginForm.

Note:
  • For the complete code, please download the sample zip file.
  • You need to use the jQuery library.
Summary
I hope this article is useful for all readers. If you have a suggestion then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode