TheDude
TheDude

Reputation: 3105

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?

Upvotes: 7

Views: 5479

Answers (1)

Lukasz Mk
Lukasz Mk

Reputation: 7350

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:

Upvotes: 8

Related Questions