在 MVC 中将分部视图渲染到布局页面的最佳方式是什么?

What is the best way to render PartialView to a Layout Page in MVC?

我的MVC5项目中有一个布局页面,我想通过单击左侧的菜单链接(超链接)来呈现所有页面内容(部分视图),如下所示.有一些方法使用 Ajax 等,但我不确定哪种方法最能满足我的需求。是否有关于此问题的示例包含 Layout 页面和 Controller 方法?

您必须先将正文内容包裹在 div 中并为其分配任何 ID:

<div id="divContentArea">
@RenderBody()
</div>

现在在脚本菜单点击事件中

$(".menuLinkItem").click(function (e) {
    e.preventDefault();        
    var controllerName = $(this).attr('data-controllername');
    var actionName = $(this).attr('data-actionname'); 

    if (String(actionName).trim() == '') {
        return false;
    }
    if (typeof (controllerName) == "undefined") {
        return false;
    }

    var url = "/" + controllerName + "/" + actionName;

    //Open url in new tab with ctrl key press
    if (e.ctrlKey) {
        window.open(url, '_blank');
        event.stopPropagation();
        return false;
    }            

    $.ajax({
        url: url,
        type: 'POST',
        success: function (data) {
            var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
            if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
                requestedUrl = window.location.href;
            }

            // if the url is the same, replace the state
            if (typeof (history.pushState) != "undefined") {
                if (window.location.href == requestedUrl) {
                    history.replaceState({ html: '' }, document.title, requestedUrl);
                }
                else {
                    history.pushState({ html: '' }, document.title, requestedUrl);
                }
            }

            $("#divContentArea").html(data);                

        },
        error: function (xhr) {
        }
    });

});

控制器:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public PartialViewResult Index()
{
        if (HttpContext.Request.HttpMethod == "GET")
        {
            return View();
        }
        else
        {
            return PartialView();
        }
}