Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

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

enter image description hereThere is a layout page in my MVC5 project and I want to render all the page contents (partial views) by clicking menu links (hyperlink) on the left side as shown below. There are some methods using Ajax, etc. but I am not sure which approach meets my needs best. Is there any example regarding to this problem containing the Layout page and Controller methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to first wrap your body content in div and assign any id to it:

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

Now in Script Menu click event:

$(".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) {
        }
    });

});

Controller:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...