CodeDigest.Com Logo
Featured:

Making Ajax Calls to Controller Action Using Asp.Net MVC Ajax Helper Methods

Tagged as: Asp.Net MVC AJAX Posted By

Ajax calls has become a default in many of web application we develop these days. Implementing Ajax calls for server communications as opposed to traditional post back based application will give greater user experience. Asp.Net MVC framework has many inbuilt HTML helper methods for making Ajax calls to controller action methods very easily. In this article, let us understand how to make Ajax calls by using the Asp.Net MVC framework’s HTML helper methods.

For easy understanding, let’s build simple application where we will display a list of employee summary with a details and delete Ajax methods. When the user click details link, it will display the employee detail in a separate details views using Ajax. Similarly, when the user clicks delete link, it will delete the employee row from the database. Refer the below screenshot.

For demonstration, we will use EF Code First and Asp.Net MVC 5.0 project in Visual Studio 2015 with a simple Employee-Department model. Assuming, you have created Asp.Net MVC 5.0 project and have included all Nuget packages for MVC and EF let’s go ahead and build the employee details view as seen in the above screenshot.

Pre-Requisite

To use the in-built Ajax helper method, we need the latest jQuery library and Microsoft.jQuery.Unobtrusive.Ajax Nuget packages. Go to the Nuget package manager and install these 2 packages into your project if not already added. If you are new to Nuget package manager, read “Using Nuget Package Manager” section under Learn Nuget Package Manager in 10 Minutes quick start article to learn to use Nuget package manager.

Employee – Details View with Ajax Helper Methods

We will use the @Ajax.ActionLink() HTML helper methods found in System.Web.Mvc.Ajax namespace to make Ajax calls. The commonly used method signature below

 

@Ajax.ActionLink(

                string linkText,

                string actionName,

                string controllerName,

                RouteValueDictionary routeValues,

                AjaxOptions ajaxOptions

)

 

 The RouteValueDictionary object in the above method can be used to pass route parameter (or input parameter) to the Ajax action method. The AjaxOptions object has many useful properties to configure the Ajax behaviour like specifying Http method, configuring target html id to populate the Ajax response, etc. There are multiple overloaded methods, but those too works similar to the above methods.

Let’s now go ahead and build the action methods and view for making the Ajax calls. The below Action method will get the list of employee from database and pass it to view to display the employee summary.

EmployeeSummary – Action method

public ActionResult EmployeeSummary()

{

   IList<Employee> empSummary = db.Employees.ToList();

   return View(empSummary);

}

                               

In the EmployeeSummary view, we have used the Ajax helper methods @Ajax.ActionLink() methods(bolded) to make the Ajax calls to action methods defined in Employee controller.

EmployeeSummary.cshtml

 

<h2>Employee List</h2>

<div>

    @Html.ActionLink("Index", "Index", "Home")

</div>

 

<div>

    <table class="table table-bordered table-condensed">

        <tr>

            <th>Name</th>

            <th>Department</th>

            <th>MVC Ajax Action</th>

        </tr>

        @foreach (Employee emp in Model)

        {

            <tr id="tr@(emp.EmployeeId)">

                <td>

                    @Html.ActionLink(String.Format("{0} {1}", emp.FirstName, emp.LastName), "Details", new { id = emp.EmployeeId })

                </td>

                <td>

                    @emp.Department.DepartmentName

                </td>

                <td>

                    @Ajax.ActionLink("Details", "detail", new { id = emp.EmployeeId }, new AjaxOptions() { UpdateTargetId = "details" }) |

                    @Ajax.ActionLink("Delete", "delete", new { id = emp.EmployeeId }, new AjaxOptions() { UpdateTargetId = "tr" + emp.EmployeeId, HttpMethod = "POST" })

                </td>

            </tr>

        }

    </table>

</div>

<div id="details">

 

</div>

 

As you see the above view code, we have configured the AjaxOptions object with the UpdateTargetId to div with id “details”. This will make sure the Ajax action method response will be populated to the details div tag. Similarly, for delete Ajax action link, it takes the UpdateTargetId as the table <tr> tag’s id to replace the content with Ajax response returned by the delete action method. The delete action link also configures Http method as Post for deletion.

The below are the action method the Ajax links will call to display employee details and delete the employee row.

Ajax Action Methods

 

public ActionResult detail(int id)
{
    return PartialView("_detail",db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault());
}

[HttpPost]
public ActionResult delete(int id)
{
    Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
    if(emp != null)
    {
        db.Employees.Remove(emp);
        db.SaveChanges();
        return Content("Deleted Successfully!");
    }
    return Content("Error!");
}
 

_detail.cshtml Partial View

@using EmployeeMaintenance.Models;

@model Employee

<h2>Employee Details</h2>

<div>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.FirstName)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.FirstName)

        </dd>

 

        <dt>

            @Html.DisplayNameFor(model => model.LastName)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.LastName)

        </dd>

         //Removed for brevity

    </dl>

</div>

 

The detail action method will return the partial view as a response to the Ajax call.

Using @Ajax.BeginForm()

We also have an alternate HTML helper method to make Ajax form submission using @Ajax.BeginForm() helper methods. The above delete Ajax implementation can be implemented using this method as seen below.

 

@using (Ajax.BeginForm("delete",new AjaxOptions() { UpdateTargetId = "tr" + emp.EmployeeId, HttpMethod = "POST" }))

{

<input type="hidden" name="id" value="@emp.EmployeeId" />

<input type="submit" value="Delete" />

}

 

Download the source attached and see it in action!



Feedback

Comments

Tnx
thank u bro, u saved my life
Commented by a noob programmer on 10/14/2019 12:05:27 AM