Why to use Ajax Actionlink in Asp.net MVC razor web page?
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.
Here is an example of how you can make Ajax call using ajax actionlink from razor view in Asp.net MVC application.
@Ajax.ActionLink("Click Me", "ActionLinkExample","aspnetmvc", new AjaxOptions { UpdateTargetId = "divAjaxResult", InsertionMode = InsertionMode.Replace, HttpMethod = "Post", 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.
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" />
Now we have seen how to make Ajax call using Ajax.ActionLink in above example, now you will learn how to add confirmation message when someone click on that link, if user click on confirm then the ajax call will be made, otherwise not.
Confirm Ajax Call Example: Click Me
Here is the code
@Ajax.ActionLink("Click Me", "ActionLinkExample", "aspnetmvc", new AjaxOptions { UpdateTargetId = "divAjaxResult1", InsertionMode = InsertionMode.Replace, HttpMethod = "GET", Confirm="Do you want to make call?" })
You also should learn