Pages

Search

Friday, January 11, 2013

Ajax Action Link


Would like to share the behaviour of “AjaxActionLink” with a sample source using MVC 4.0.
As know, ajax action link helps to perform ajax callbacks invoking an action from controller and then binding the result to the target object.
In MVC 3.0 and 4.0, has come with rendering html page that works with HTML 5. Hence the HTML elements are rendered in the browser with an extra set of elements that help to perform ajax calls instead of rendering the JSON objects which use to happen in MVC 2.0.

For a given Ajax Action link in View,

@Ajax.ActionLink("Server Date Time", "ServerDate"
, new AjaxOptions() { HttpMethod = "GET", InsertionMode= InsertionMode.Replace, UpdateTargetId="div_serverdate"})
Server Date Time :
 <div id="div_serverdate">
 </div>

Page source in MVC 2.0

<a href="/Home/ServerDate" onclick="Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: &#39;GET&#39;, updateTargetId: &#39;div_serverdate&#39; });">Server Date Time</a>
  Server Date Time :
 <div id="div_serverdate">
 </div>

Page source in MVC 4.0
 
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#div_serverdate" href="/Home/ServerDate">Server Date Time</a>

  Server Date Time :


 <div id="div_serverdate">


 </div>

But need to note that in case of MVC 2.0, MicrosoftMVCAjax.js, has required functions to perform callbacks.
In case of MVC 3.0 or 4.0, there is a new js file jquery.validate.unobtrusive.js. This file has to be refered in the view or layout page. This js files deals with the HTML 5 elements.
Also, need to cross check if the web.config has the “UnobtrusiveJavaScriptEnabled” flag set to true.

If this is set to false, then it implies the MVC2.0 approach.
Controller Code :
       [HttpGet]
        [OutputCache( NoStore=true,Duration=0)]
        public ContentResult ServerDate()
        {
            return Content(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
        }
View :

@{
    ViewBag.Title = "Contact";
}
@Ajax.ActionLink("Server Date Time", "ServerDate"
, new AjaxOptions() { HttpMethod = "GET", InsertionMode= InsertionMode.Replace, UpdateTargetId="div_serverdate"})
Server Date Time :
 <div id="div_serverdate">
 </div>

Before clicking on Link

 


After Clicking on Link (response rendered to div, without page post back or reload).


No comments:

Post a Comment