Working with AJAX in MVC application


In this article we are going to focus on Working with AJAX in MVC application. We are using AJAX because we would like to avoid reloading the complete page whenever the form is submitted to the server.

In this article we are going to focus on Working with AJAX in MVC application. We are using AJAX because it is asynchronous and it can partially load the page. It requests data from the server in the background without reloading the page. The MVC Framework unobtrusive Ajax feature is based on jQuery.

Step 1
Create a new MVC Application with basic Template and name it "MVCUnobtrusiveAjaxDemo".
This will create a basic skeleton for our MVC application with the basic Controllers/Views/Models folders.

Step 2
Right-Click Models folder and Add Class Emp with the following code.


public class Emp
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
public Dept Department { get; set; }
}

public enum Dept
{
IT,
Sales,
HR,
Marketing,
Admin
}

We have a Emp class and an enum Dept which is used in Emp class to represent the department of each employee.

Step 3
Right-Click controllers folder and add New Controller with the name "EmpController". Write the following code in the EmpController class

public class EmpController : Controller
{
private Emp[] EmpData = {
new Emp {Id=1,Name = "Riya", Department = Dept.IT,Salary=9000},
new Emp {Id=2,Name = "Sam", Department = Dept.Sales,Salary=1000},
new Emp {Id=3,Name = "Mary", Department = Dept.HR,Salary=34000},
new Emp {Id=4, Name = "John", Department = Dept.IT,Salary=20000},
};

public PartialViewResult GetEmpInfo(string selectedDept="All")
{
if(selectedDept == null || selectedDept== "All")
{
return PartialView(EmpData);
}
else
{
Dept dept = (Dept)Enum.Parse(typeof(Dept), selectedDept);
var result = EmpData.Where(d => d.Department == dept);
return PartialView(result);
}
}

public ActionResult GetEmpData(string selectedDept = "All")
{
return View((object)selectedDept);
}

Step 4
Right-Click the GetEmpData action method in the EmpController class and choose Add View. Keep the view name as it is which would be "GetEmpData". This will create "GetEmpData.cshtml" file in the /Views/Emp/ folder.
Step 5
Similarly Right-Click the GetEmpInfo action method in the EmpController class and choose Add View. Keep the view name as it is which would be "GetEmpInfo". This will create "GetEmpInfo.cshtml" file in the /Views/Emp/ folder.

Step 6
Copy and paste the below code in the GetEmpData.cshtml file


@using MVCUnobtrusiveAjaxDemo.Models
@model string
@{
ViewBag.Title = "GetEmpInfo";
AjaxOptions ajaxOpts = new AjaxOptions();
ajaxOpts.UpdateTargetId = "tbody";
ajaxOpts.LoadingElementDuration = 1000;
ajaxOpts.LoadingElementId = "loading";
}
<div id="loading" class="load" style="display:none">
<p>Loading Data...</p>
</div>

<h2>Get Emp Data</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Department</th>
</tr>
</thead>
<tbody id="tbody">
@Html.Action("GetEmpInfo", new { selectedDept = Model })

</tbody>
</table>
@* When we set up our Ajax-enabled form as shown below, we passed in the name of the action method that
we wanted to be called asynchronously i.e., the GetEmpInfo action, which
generates a partial view containing a fragment of HTML. *@
@using (Ajax.BeginForm("GetEmpInfo",ajaxOpts))
{
<div>@Html.DropDownList("selectedDept",new SelectList(new[]{"All"}.Concat(Enum.GetNames(typeof(Dept)))))
<button type="submit">Submit</button></div>

}


MVC Framework supports AJAX forms using the Ajax.BeginForm helper method. The first parameter to this method is the name of the action method that will handle the request and the second parameter is AjaxOptions object which we have created at the start of the view in the Razor code block.
AjaxOptions class defines properties that can be used to configure how asynchrounous request to the server is made and how the data we get from the server is processed.
In the AjaxOptions object we have set the UpdateTargetId property value to "tbody", which is the id we have assigned to the tbody HTML element in the view.
LoadingElementId: Id of the HTML element that will be displayed while the Ajax request is being processed at the server side.
LoadingElementDuration: The duration of the loading message that is used to reveal the loading element to the user.
When the user hits the Submit button, an asynchronous request will be made to the GetEmpInfo action method and the HTML markup that is returned is used to replace the existing elements in the tbody.
Step 7
Copy and paste the following code in GetEmpInfo.cshtml file

@using MVCUnobtrusiveAjaxDemo.Models
@model IEnumerable<MVCUnobtrusiveAjaxDemo.Models.Emp>

@foreach(Emp e in Model)
{
<tr>
<td>@e.Name</td>
<td>@e.Salary</td>
<td>@e.Department</td>
</tr>
}

Please note the following points about the above view:
1. Here GetEmpInfo is a strongly-typed view whose model type is IEnumerable<Emp>.
2. We are enumerating the Emp objects in the model to create rows in an HTML table.
Step 8
Open the _Layout.cshtml file in the /Views/Shared folder and make sure that you have reference to the files : "jquery-1.8.2.min.js", "jquery.unobtrusive-ajax.js" in the head section as shown below:


<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript">
</script>

The jquery-1.8.2.min.js file contains the core jQuery library.
The jquery.unobtrusive-ajax.min.js file contains the Ajax functionality.

Step 9
In the Web.config file of the root folder, make sure that configuration/appSettings element contains an entry UnobtrusiveJavaScriptEnabled which is set to true.

Step 10
Build and Run the application. Navigate to http://localhost:3907/Emp/GetEmpData
Here port number may vary based on your project settings. This will result in the output as shown below:
ajaxoutput
Step 11 Let us filter the Emp data by selecting "IT" department and then click on Submit. While the request is submitted to the server and it is processing the UI displays the Loading... message until we get the output from the server. Once the data is filtered. The output is as shown below:
filtereddata

Please note that the above code will work only if the Javascript is enabled in the browser. If javascript is disabled, The output with Emp data filtered by HR department will be displayed in another page as shown below:
disablejs

To see this in action, you can disable javascript in IE 10 by following the below steps: Open IE browser window -> Tools -> Internet Options -> Security -> Internet -> Custom Level -> Security Settings - Internet Zone -> Scripting ->Active Scripting -> Disable. Now run the application and see the output as shown above.


Comments

Author: Dotnet Developer-201531 Aug 2015 Member Level: Gold   Points : 0

Hi
Vaishali

I try this article but i meet this issue how to fixed this?

Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

Can you share the Source code for this can you send mail



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: