简体   繁体   中英

ASP.NET MVC Partial Views + Ajax Load

I am working on a project and in order to not have the Layout view being reloaded with every page change, I decided to change my views to partial views. In order to load the views when a user clicks on one of the menu items in the navigation menu I am now using jquery ajax like the following:-

$("ul.metismenu a:not(.subMenuParent)").unbind().click(function (e) {

    e.preventDefault();

    var url = $(this).attr("href");
    window.history.pushState("", "", url);

    $.ajax({
        url: url,
        dataType: 'html',
        success: function (data) {

            $('#page-content').html(data);

        }
    });
});

The element page-content resides in the Layout view. It is working fine, however the issue I am encountering now is that when i try to access the View directly say i go /Dashboard directly in the browser I will get just the partial view, without the Layout page. Anyone got some ideas how I can solve this please? Thank you in advance for any advice.

You can have different layout set from different controller actions by using a variable. Even a ViewBag would suffice. For the action Dashboard , you can set the ViewBag.Layout (say) to the Layout html and for the partial view you can set ViewBag.Layout to empty. THen use this variable in the html page. So, the right layout will be picked up depending on the action we are calling.

您的网址调用MVC Action ,让您返回ActionResultPartialView()

I was able to fix the issue by first checking if the request coming is an ajax request or not. Then depending on the type of request i set the Layout view. This is a sample code from an action:-

    public ActionResult Index()
    {
        if (!Request.IsAjaxRequest())
        {
            ViewBag.Layout = "~/Views/Shared/_Layout.cshtml";
        }
        return PartialView();
    }

And in the partial view i set the following:-

  @{ 
      Layout = ViewBag.Layout; 
   }

Hope this helps someone who might encounter the same issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM