Monday 4 March 2013

ASP.NET MVC Unobtrusive Ajax


Unobtrusive Ajax: 
The MVC Framework contains support for unobtrusive Ajax like Ajax link and Ajax form. To enabled unobtrusive Ajax below js file should be include in view.

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Ajax Form: To create an Ajax-enabled form we have to define following in view.


  • Ajax Options
  • Ajax Begin Form

      Ajax options: The AjaxOptions class has a set of properties that let us configure how the asynchronous request to the server is made and what happens to the data that we get back.

Property
Description
Confirm
Displays a confirmation message before making the Ajax request
HttpMethod
Use to set the HTTP method to make the request like Get or Post.
InsertionMode
Option to set Ajax response content in HTM. Optins are “InsertAfter”, “InsertBefore”, and “Replace” (the default)
LoadingElementId
Specifies the ID of an HTML element that will be displayed while the Ajax request is being performed.
LoadingElementDuration
Specifies the number of milliseconds to LoadingElement will appear while Ajax calls.
UpdateTargetId
Sets the ID of the HTML element into which the content retrieved from the server will be inserted.
Url
URL that will be requested from the server.

When using the Ajax.BeginForm helper method, we passed the name of the action method that the asynchronous request should be made to and the AjaxOptions object that configures the request.

Example:
@model IEnumerable<MVCValidation.Models.RegisterModel>
@{
    ViewBag.Title = "Users";
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "result",
        Url = Url.Action("SearchedUsers"),
        LoadingElementId = "loading",
        LoadingElementDuration = 3000,
        Confirm = "Are you sure to request new data?",
        InsertionMode = InsertionMode.InsertBefore
    };
}

@using (Ajax.BeginForm("SearchedUsers", ajaxOpts)) {
<p>
@Html.DropDownList("userName", new SelectList(
            new[] { "All", "User1", "User2", "User3" }, "All"))
<input type="submit" value = "Submit" />
</p>
}

<div id="loading" style="display:none; color:Red; font-weight: bold">
<p>Please wait...</p>
</div>

<div id="result">
</div>

public PartialViewResult SearchedUsers(string userName)
{
     List<RegisterModel> users = UserHelper.GetUsers();
     users = users.FindAll(c => c.UserName == userName);
     return PartialView("SearchedUsers",users);
}

Ajax Links: Ajax helper method ActionLink use to asynchronously request when user clicks on link.

Example:

AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "userResult",
        LoadingElementId = "loading",
    };

<div id="userResult">
</div>


@Ajax.ActionLink("Details", "UserDetails", new { @userName = Model.UserName }, ajaxOpts)

public ContentResult UserDetails(string userName)
{
     RegisterModel user = UserHelper.GetUsers().Find(c => c.UserName == userName);
     StringBuilder sb = new StringBuilder();
     sb.Append("User Detail: ");
     sb.Append("UserName: " + user.UserName);
     sb.Append(" Email: " +  user.Email);

     return Content(sb.ToString());
}


Ajax Callbacks: The AjaxOptions class defines a set of properties that allow us to specify JavaScript functions that will be called at various points in the Ajax request life cycle.

Property
jQuery Events
Description
OnBegin
beforeSend
Called prior to the request being sent
OnComplete
complete
Called if the request is successful
OnFailure
error
Called if the request fails
OnSuccess
success
Called when the request has completed, irrespective of whether the request succeeded or failed.


Ajax callbacks properties takes name of JavaScript functions which executes while Ajax  request cycle.

Example:

AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "result",
        OnBegin = "OnBegin",
        OnFailure = "OnFailure",
        OnSuccess = "OnSuccess",
        OnComplete = "OnComplete"
    };

<script type="text/javascript">
    function OnBegin() {
        alert("This is the OnBegin Callback");
    }
    function OnSuccess(data) {
        alert("This is OnSuccess Callback: " + data);
    }
    function OnFailure(request, error) {
        alert("This is OnFailure Callback:" + error);
    }
    function OnComplete(request, status) {
        alert("This is  OnComplete Callback: " + status);
    }
</script>

6 comments:

  1. Excellent article....Thanks for the good work.

    ReplyDelete
  2. Nice blog , Thanks for sharing informative blog with us and i bookmark this blog for the future purpose.

    dot net development services

    ReplyDelete
  3. What is the difference between custom controls and user controls? Please Briefly Explain the Usage of Global.asax?

    Top 8 Medical Websites Designed by Optimized360.Com

    ReplyDelete
  4. Nice information, thanks for sharing this informative content in this blog and i bookmark this information for future use.

    Enterprise Website Development Company

    ReplyDelete