After adding this script AJAX helper intelligence is now available in a view and layout page.
Now it’s time to add script reference in a view or layout page. NOTE: if your application is making too many AJAX requests throughout the project it is better to add a reference in a layout page. In the code sample I have added this script reference in _Layout page just below the jquery.min.js script reference.
- <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
We have seen that both HTML helper and AJAX helper method generate the anchor tag, now the question is where to use the
@HTML.ActionLink and
@AJAX.ActionLink.
For that consider the following situation.
Whenthe user clicks on the link and you want to redirect user to another different page in that situation you have to use @HTML.ActionLink.
When the user clicks on the link and you don’t want to redirect to different page, but you want them to stay on the same page and display some information or details without Post Back, at that time it’s better to use @AJAX.ActionLink.
@AJAX.ActionLink has 12 different overloads; here I have explained the most important one that is mostly used.
In the sample code I have used ASP.NET MVC5 applications using the Entity Framework 6 and Visual Studio 2015. For more information about how to work with Entity Framework Getting Started with Entity Framework 6 using MVC 5
@AJAX.ActionLink Example
1. Create AJAX action link,
/Views/Home/Index.cshtml
- @Ajax.ActionLink("View All Student Info", "AllStudent", "Home", new AjaxOptions
- {
- UpdateTargetId = "divAllStudent",
- OnBegin = "fnOnBegin",
- InsertionMode = InsertionMode.Replace,
- HttpMethod = "GET",
- LoadingElementId = "imgloader",
- OnSuccess= "fnSuccess",
- Confirm="Do you want to get all student info ?????"
- }, new { @class = "btn btn-default" })
/Controllers/HomeController.cs
2. Create action method.that will call on action click event.
- [HttpGet]
- public PartialViewResult AllStudent()
- {
- using (TempEntities db = new TempEntities())
- {
- var objAllStudent = db.StudentInfoes.ToList();
- return PartialView("AllStudent", objAllStudent);
- }
- }
Views/Home/AllStudent.cshtml
3. creating a partial view that will return all student info.
- @model IEnumerable<StudentInfo>
- <table class="table">
- <tr>
- <th>@Html.DisplayNameFor(model => model.FirstName)</th>
- <th>@Html.DisplayNameFor(model => model.LastName)</th>
- <th> @Html.DisplayNameFor(model => model.MobileNo)</th>
- <th>@Html.DisplayNameFor(model => model.Address)</th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td> @Html.DisplayFor(modelItem => item.FirstName)</td>
- <td>@Html.DisplayFor(modelItem => item.LastName)</td>
- <td>@Html.DisplayFor(modelItem => item.MobileNo)</td>
- <td> @Html.DisplayFor(modelItem => item.Address)</td>
- </tr>
- }
- </table>
In @Ajax.ActionLink,First parameter is the link text that will be displayed on the User Interface. Second parameter is an action method name that you want to call asynchronously. Third parameter is name of controller. Now the most important parameter is AjaxOptions. The following different options are available in AjaxOptions class.
Allowcache
Confirm
HttpMethod
InsertionMode
LoadingElementDuration
LoadingElementId
OnBegin
OnComplete
OnFailure
OnSuccess
UpdateTargetId
Url
1. AllowCache:
By Default it is false, it specifies whether you want to cache the page requested by the browser or not by specifying its value as true or false.
2. Confirm:
This is the parameter that executes first if you have specified. This property is used to specify what message text will be displayed in a confirmation window before request is submitted.i.e when you click on “View All Student Info” link. It will display confirmation window before sending AJAX request.
3. HttpMethod: Specifies the HTTP request method. that is either GET or POST. by default it is POST.
4. InsertionMode:
This enumeration property specifies how to insert the response coming back from the action method into the target DOM element (here DOM element is <div> tag UpdateTargetId = "divAllStudent"). In the above example I have specified the InsertionMode as a Replace mode so whatsever the response coming back will be inserted into
- <div id="divAllStudent"></div>.
InsertionMode enumeration contain four different value.
4.1 InsertAfter
4.2 InsertBefore
4.3 Replace
4.4 ReplaceWith
Default InsertionMode value is “Replace”.
5. LoadingElementDuration: Here you can specify the value in milliseconds that controls the duration ofthe animation loading element.
6. LoadingElementId: HTML element that will be displayed when AJAX call is in-progress.
Generally we used this property to display the loader element.i.e.
- <div id="imgloader" style="display:none;position:absolute;top:50%;left:50%;padding:2px;">
- <img src="~/Content/loader.gif" />
- </div>
7. OnBegin:
This property specifies the name of the java script function that is called just before Ajax starts. so here you can perform some validation or other operation that is required before Ajax starts. i.e OnBegin = "fnOnBegin",
- <script type="text/javascript">
- function fnOnBegin() {
- if ($("#txtSearchValue").trim() == null)
- {
- return false;
- }
- return true;
- }
- </script>
8. OnComplete: name of the java script function that will be called when response data has been represented by the AJAX call.
9. OnFailure: name of the java script function to call when AJAX request returns error.
10. OnSuccess:
name of the java script function to call after the AJAX request returns successfully. You can also check the AJAX call return status in browser,i.e press Ctrl+Shift+i and goto Network tab.
- <script type="text/javascript">
- function fnSuccess() {
- alert("Booo..Success..");
- }
- </script>
11. UpdateTargetId:
This property is used to specify the ID of HTML element that is updated by using the response; i.e, here I have specified the div element with the id “divAllStudent”.
- <div id="divAllStudent" class="col-md-12">
- </div>
12. URL: specify the URL to make call.i.e External URL link.
@AJAX.BeginForm Example
1. create AJAX form
/Views/Home/Index.cshtml
- @using (Ajax.BeginForm("SearchStudent", "Home", new AjaxOptions
- {
- InsertionMode = InsertionMode.Replace,
- HttpMethod = "GET",
- LoadingElementId = "imgloader",
- OnFailure = "fnError",
- OnBegin = "fnOnBegin",
- UpdateTargetId = "divSearchStudent",
- }))
- {
- <div class="form-horizontal">
- <div class="form-group">
- Student Name:
- <input type="text" name="SearchTerm" placeholder="Keyword" class="form-control" />
- </div>
- <div class="form-group">
- <input type="submit" value="Search" class="btn btn-default" />
- </div>
- </div>
- }
- <div id="divSearchStudent"></div>
2. Create action method that will called asynchronously when form is submited.
/Controllers/HomeController.cs
- [HttpGet]
- public ActionResult SearchStudent(string SearchTerm)
- {
- if (SearchTerm != null)
- {
- using (TempEntities db = new TempEntities())
- {
- var objSearchStudent = db.StudentInfoes.Where(x => x.FirstName.Contains(SearchTerm) ||
- x.LastName.Contains(SearchTerm) ||
- x.MobileNo.Contains(SearchTerm) ||
- x.Address.Contains(SearchTerm)).AsEnumerable().Select(x => new StudentInfo
- {
- Address = x.Address,
- FirstName = x.FirstName,
- LastName = x.LastName,
- MobileNo = x.MobileNo
- });
- return PartialView("AllStudent", objSearchStudent.ToList());
- }
- }
- return View();
- }
When you click on the search button, an asynchronous request is sent to the “SearchStudent” action method inside the home controller and all the form data is submitted to action method. This action method returns the partial view content that will be placed inside the “divSearchStudent” DOM element.
Read more articles on AJAX: