WebTrainingRoom Online Courses
Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Ajax.Actionlink AjaxOptions MVC Example

Ajax ActionLink is very useful, one of the best way to make Ajax Call, think of situation where you want to display data based on user item click, or more information about any product when user click on link like "more info" etc.

Ajax ActionLink Example

@Ajax.ActionLink("Click Me", "ActionLinkExample","aspnetmvc",
new AjaxOptions
    UpdateTargetId = "divAjaxResult",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    Confirm="Do you want to make this call"
@Ajax.ActionLink("Text", "ActionName", "ControllerName", AjaxOptions);

You need to remember four important parameters in @Ajax.ActionLink,
First parameter is the TEXT that will be displayed on webpage.
Second parameter is an Action Name, that you want to call asynchronously.
Third parameter is Controller Name.
Fourth is the most important parameter is AjaxOptions, which is a class

There are many different options are available in AjaxOptions class.
  • Confirm
  • Allowcache
  • HttpMethod
    Specify the HttpMethod of the call, like POST or Get
  • InsertionMode
    This is basically a enum, you can specify how you want the content to be updated, like InsertionMode.Replace
  • OnSuccess
    Specify the javascript function name, that you want to be executed if the ajax call made successfully
  • UpdateTargetId
    Mention the id of your html container like div or span, where you want action result to displayed
  • OnBegin
  • OnComplete
  • OnFailure
    Specify the javascript function name, that you want to be executed if the ajax call fail

Make sure you have a div with same id in your currect html page

<div id="divAjaxResult"> </div>

Now let's look at the server side code written in controller, we can write any action type like JsonResult or PartialViewResult

public JsonResult ActionLinkExample()
    string result = string.Format("Ajax call made at {0}",DateTime.Now);
        return Json(result, JsonRequestBehavior.AllowGet);

Also can send a partial view, Here is an example of PartialViewResult action method

public PartialViewResult ActionLinkExample()
    return PartialView("_noteView");

In above action we have passed a simple string, you can pass any complex object using json

Ajax Call Example: Click Me

Make sure you have unobtrusive JavaScript is enabled in your web.config (it should be there by default)

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

Name Email Website