We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Saturday, September 19, 2015

IMPLEMENT AJAX IN MVC?

We can implement AJAX in two ways in MVC:
->AJAX libraries
->jQuery

Below is a simple sample of how to implement AJAX by using the “AJAX” helper library. In the below code we can see we have a simple form that is created by using the Ajax.BeginForm syntax. This form calls a controller action called getCustomer. So now the submit action click will be an asynchronous AJAX
call.


<div>
    @{
        var AjaxOpt = new AjaxOptions { OnSuccess = "OnSuccess" };
    }
    @using (Ajax.BeginForm("getCustomer", "MyAjax", AjaxOpt))
    {
        <input id="txtCustomerCode" type="text" /><br />
        <input id="txtCustomerName" type="text" /><br />
        <input id="Submit2" type="submit" value="submit" />
    }

</div>

In case you want to make AJAX calls on hyperlink clicks, we can use the Ajax.ActionLink function as shown in the below code.

@Ajax.ActionLink("Update Time")


So if we want to create an AJAX asynchronous hyperlink by name GetDate which calls the GetDate function in the controller below is the code for that. Once the controller responds, this data is displayed in the HTML DIV tag named DateDiv.

<span id="DateDiv" />

@Ajax.ActionLink("Get Date", "GetDate",

new AjaxOptions { UpdateTargetId = "DateDiv" })

Below is the controller code. We can see how the GetDate a function has a pause of 10 seconds.

    public class Default1Controller : Controller
    {
        public string GetDate()
        {
            Thread.Sleep(10000);
            return DateTime.Now.ToString();
        }
    }

The second way of making an AJAX call in MVC is by using jQuery. In the below code we can see we are making an AJAX POST call to a URL /MyAjax/get customer. This is done by using $.postAll this logic is put into a function called and you can make a call to the function on a button or a hyperlink click event as we want.

   function GetData()
    {
        var url = "/MyAjax/getCustomer";
        $.post(url, function (data)
        {
            $("#txtCustomerCode").val(data.CustomerCode);
            $("#txtCustomerName").val(data.CustomerName);
        }
       
    }

No comments: