Monday, 24 December 2018

What is the use of _ViewStart.cshtml

_Layout.cshtml is the file where we keep all common view related code. But when we want to refer this common code, we need to call _Layout.cshtml file in every place, which is not a good practice. To overcome this problem we can place _Layout.cshtml file in one place i.e _ViewStart.cshtml file. Once we place anything inside this we no need to refer in any other view. It will automatically push all the logic to every view. If you want to override this we can create another _ViewStart file in a specific folder where the view on that folder will refer to that file.

Layout file can also be specified in a controller action method or in an action filter.

public ActionResult Create()
{
    return View("Create", "_Layout");
}


We can also write some logic in "_ViewStart.cshtml" to dynamically specify which layout file to use. For example, the following code will change the layout file to use based on the browser type. 

@{
    Layout = Request.Browser.IsBrowser("Chrome") ? "~/Views/Shared/_Layout.cshtml" : "~/Views/Shared/_DifferentLayout.cshtml" ;
}

No comments:

Post a Comment