簡體   English   中英

在MVC中將PartialView呈現到布局頁面的最佳方法是什么?

[英]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();
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM