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

前端 未结 2 1652
忘掉有多难
忘掉有多难 2021-02-20 05:03

I\'ve looked at few examples where Ajax can be used to update divs or other elements with ids. I have not been able to find an example that uses Ajax with Razor views to help me

2条回答
  •  旧巷少年郎
    2021-02-20 05:50

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

    
    
    $(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 }
    

    Home/About

    Blah...

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

    @Html.ActionLink("About", "About", "Home", null, new { @class="menu-button" })
    
    $(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 { })
    

提交回复
热议问题