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

前端 未结 1 349
执念已碎
执念已碎 2020-12-11 13:37

There 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 show

1条回答
  •  醉梦人生
    2020-12-11 14:22

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

    @RenderBody()

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

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