Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Request or IQueryCollection in Layout.cshtml in ASP.NET Core MVC?

Is it possible to access the Request or IQueryCollection within a view, and specifically within _Layout.cshtml? The reason for this is to conditionally render elements in Razor based on the query string. Obviously this isn't ideal but this is a legacy application.

like image 336
user9993 Avatar asked Apr 28 '19 17:04

user9993


People also ask

What is layout Cshtml in MVC?

The file MasterLayout. cshtml represents the layout of each page in the application. Right-click on the Shared folder in the Solution Explorer, then go to Add item and click View.

Which directive help a Cshtml file handle request directly?

@page makes the file into an MVC action, which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page.

What is the purpose of _layout Cshtml?

_Layout.cshtml This is used for common layout in web pages; it is like master page. The layout typically includes common user interface elements such as the app header, navigation or menu elements, and footer. Common HTML structures such as scripts and stylesheets are also frequently used by many pages within an app.

What is @model in Cshtml?

The @model directive allows access to the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object: CSHTML Copy.


1 Answers

You can access IQueryCollection inside of any Razor View via the Context property, which is an instance of HttpContext. Here's an example:

<p>Foo: @Context.Request.Query["Foo"]</p>

See the docs here: Use HttpContext from a Razor view .

like image 180
Kirk Larkin Avatar answered Sep 21 '22 01:09

Kirk Larkin