How to use Ajax to update RenderBody() section with VS 2012 Internet Template? How to use Ajax to update RenderBody() section with VS 2012 Internet Template? ajax ajax

How to use Ajax to update RenderBody() section with VS 2012 Internet Template?


Here is a simple example with jquery. The About partial gets injected into the div with id="body".

<button>About</button><div id="body"></div>$(function () {    $("button").on("click", function(e) {        $.get("Home/About").done(function(result) {            $("#body").html(result);        });    });));

Controller Action

[HttpGet]public ActionResult About(){    return PartialView("About");}

About.cshtml

@{ Layout = null }<h2>Home/About</h2><p>Blah... </p>

Edit: Maybe a better example is to use a link instead

@Html.ActionLink("About", "About", "Home", null, new { @class="menu-button" })<div id="body"></div>$(function () {    $(".menu-button").on("click", function(e) {        e.preventDefault();        var url = $(this).attr("href");        $.get(url).done(function(result) {            $("#body").html(result);        });    });});

Edit: Without jquery you want to use Ajax.ActionLink() instead of Ajax.BeginForm()

@Ajax.ActionLink("About", "About", "Home", null, new AjaxOptions { HttpMethod = "get", UpdateTargetId = "body" }, new { })<div id="body"></div>


In your HomeController.cs

public PartialViewResult About(){    ViewBag.Message = "Your app description page.";    return PartialView();}

In your _Layout.cshtml do not forget to import:

    <script src="~/Content/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>    <script src="~/Content/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>