How can I code a refresh of a HTML.RenderPartial using Ajax in MVC3?

后端 未结 2 1582
鱼传尺愫
鱼传尺愫 2020-12-21 14:29

I have the following view:

    @model ViewModels.Shared.BaseViewModel
    
相关标签:
2条回答
  • 2020-12-21 14:33

    You need a child action, not a partial view.

    You can then write

    <div id="#thingy">@Html.Action("Detail", new { ac, me })</div>
    
    $('#thingy').load("@Server.JavaScriptStringEncode(Url.Action("Detail", new { ac, me }))");
    
    0 讨论(0)
  • 2020-12-21 14:43

    The basic idea will be that you will use JQuery to fire off an AJAX request when you want your Partial View updated.

    The AJAX request will call one of your controller actions, which then will return a PartialViewResult.

    The 'success' part of the JQuery AJAX result will get the HTML response, and replace a given container in your View with the new HTML.

    e.g.

    Your View could look like this:

    @model ViewModels.Shared.BaseViewModel
    <script type="text/javascript">
        $(function () {
            $('#RefreshButton').click(function () {
                $.ajax({
                    url: *href*,
                    dataType: 'html',
                    cache: false,
                    success: function (responseText) {
                        $('#PanelToUpdate').html(responseText);
                    }
                });
            });
        });
    </script>
    <div id="PanelToUpdate" class="rep_tb0">
        <div class="rep_tr0">
            <div class="rep_td0">@Html.LabelFor(model => Model.Link.Position)</div>
            <div class="rep_td0">@Html.LabelFor(model => Model.Link.Title)</div> 
        </div>
        @for (var i = 0; i < Model.AdminDetails.Count; i++)
        {
            var qs = "&ac=" + Model.Meta.AccountID +
                        "&me=" + Model.AdminDetails[i].RowKey;  
        <div class="rep_tr0">
            <div class="rep_td0">
                @Html.TextBox(("Position_" + @i), Model.AdminDetails[i].Position, new { size = 2 })
            </div>
            <div class="rep_td0">@Model.AdminDetails[i].Title</div>             
        </div>  
        }
    </div>    
    <button id="RefreshButton"></button>
    

    where href is the URL for your controller action. Aternatively, you could look at an AJAX post method and serialize your form data, if that is needed.

    Then, a small tweak to your controller action, so that it can handle being called either via AJAX or normally:

    public ActionResult Detail(string ac, string me)
    {
        vm.AdminDetails = _link.Detail(ac + me).ToList();
    
        if (Request.IsAjaxRequest())
            return PartialView(vm);
        return View(vm);
    }
    

    Without the return PartialView(vm); the HTML response for the AJAX request would include your pages header

    0 讨论(0)
提交回复
热议问题