A day with .Net

My day to day experince in .net

Ajax in MVC 4

Posted by vivekcek on May 27, 2013

In MVC 4 the ajax related functions are included in a JS file named ‘jquery.unobtrusive-ajax.js’. So to include this file in our view’s, follow the below steps.

1. In BundleConfig.cs register our script bundle by adding the below code after all defult bundle registrations.

 bundles.Add(new ScriptBundle("~/bundles/Custom").Include(
                 "~/Scripts/jquery.unobtrusive-ajax.js"));

2. Now at the bottom of your master page _Layout.cshtml, add the below code.

@Scripts.Render("~/bundles/Custom");

3. Now in your Home View add this code.

<div id="timeDiv">
@Ajax.ActionLink("Click to get Server time", "GetServerTime", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "timeDiv"
})
</div>

4. In home controller.

 public class HomeController : Controller
    {
        public string GetServerTime()
        {
            return DateTime.Now.ToLongDateString();
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s