Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC way to pass data to _layout.cshtml?

I keep reading that the MVC way to pass data from a controller to the view is done via a ViewModel, but what about passing data to _Layout.cshtml, like page title, meta description, article author, etc...

What's the MVC way to pass this kind of data? Should I just use ViewBag for them?

like image 912
TheDude Avatar asked Dec 23 '16 20:12

TheDude


People also ask

How do you pass ViewBag data from controller layout?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

What is _layout Cshtml in MVC?

The file "_Layout. cshtml" represents the layout of each page in the application. Right-click on the Shared folder in Solution Explorer then go to "Add" item and click on "View". Now the View has been created.


1 Answers

You have few ways:

  • ViewBag
  • ViewData
  • View Components
  • Injections (example below)


ViewBag and ViewData are quite easy to use, however not always convenient.

There is one big plus - you could set/read them in one place of view and read in another - for example, you could set them in your main view and read/display them in _lauout.cshtml.


View Components are the most interesting new feature in MVC Core (in my opinion) which allows you to create UI widgets.

There is a little bit more coding for ViewComponent (you need to create controller and view), but it's flexible feature (I like it) and easy to call in a place where you need it, just

@await Component.InvokeAsync("NameOfCOmponent").


Injections not my favorite, but sometime usfull - for example if you want display user name, you could just put the following code directly into your layout/view file:

@using System.Security.Claims
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> userManager
@{
    var userInfo = ((await userManager?.GetUserAsync(User))?.xxx);
    // where 'xxx' is any property of ApplicationUser model
}

then you can use @userInfo in the same view to display that info.


More information:

  • Views Overview
  • Passing Data to Views
  • View Components
like image 166
Lukasz Mk Avatar answered Sep 25 '22 06:09

Lukasz Mk