Display layout only when view is not loaded via ajax

3

In my project, I'm developing so that the application works even if the user is disabled or unavailable. If JavaScript is not available, I load the page normally. If it is available, I load some of these pages in modal so that the flow is more fluid.

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

@{
    Layout = null;
}

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

    
asked by anonymous 14.03.2014 / 21:02

2 answers

4

Indicating the view master on the controller

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

In the view delete this line:

Layout = "_Layout.cshtml"; // elimine

In your action do so:

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

So you can use the same view for both request types.

Varying the view according to the request

Or if you want to do this in the same view:

Layout = this.Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
    
14.03.2014 / 21:23
3

Better to do in Controller :

public ActionResult Index()
{
    if (Request.IsAjaxRequest())
        return PartialView("partialView");
    else
        return View();
}
    
14.03.2014 / 21:04