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?
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.
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.
You have few ways:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With