Display layout only when view is not loaded via ajax

Asked

Viewed 330 times

3

In my project, I am developing so that the application works even if the user is with Javascript disabled or unavailable. If Javascript is not available, I load the page normally. If available, I upload some of these pages into a modal so that the flow becomes more fluid.

To control the look of these pages, each view inherits the default layout of my application through the file _viewstart.cshtml. What I would like is that when the page is loaded via ajax, this layout is not used, which is equivalent to this:

@{
    Layout = null;
}

How can I achieve this (preferably without relying on extra variables, either in the URL or via @ViewBag)?

2 answers

4


Indicating the master view in the controller

One way to do this is not set the layout in the view, but in the controller:

In the view delete that line:

Layout = "_Layout.cshtml"; // elimine

In your action do so:

if (Request.IsAjaxRequest())
    return PartialView("NomeView");
else
    return View("NomeView", "_Layout");

Thus, you can use the same view for both types of request.

Varying the view according to the request

Or if you want to do it in the view:

Layout = this.Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
  • 2

    It seemed the best approach, given that I use my layout in a _viewstart! Thank you. I used the third approach in a block if simple.

3

Better do in the Controller:

public ActionResult Index()
{
    if (Request.IsAjaxRequest())
        return PartialView("partialView");
    else
        return View();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.