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

前端 未结 2 1673
忘掉有多难
忘掉有多难 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".

    <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>
    
    0 讨论(0)
  • 2021-02-20 05:53

    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>
    
    0 讨论(0)
提交回复
热议问题