6

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?

TheDude
  • 3,045
  • 4
  • 46
  • 95
  • Possible duplicate of [Pass data to layout that are common to all pages](http://stackoverflow.com/questions/13225315/pass-data-to-layout-that-are-common-to-all-pages) – DavidG Dec 23 '16 at 20:18
  • 2
    You can use a ViewBag for page title, yes. You could also make that a model property and bind your Layout.cshtml file to that view model. You could also use session data. You have lots of options here – mituw16 Dec 23 '16 at 20:18
  • ViewBag is easiest. But you can also use a [Child Action](http://stackoverflow.com/questions/12530016/what-is-an-mvc-child-action). – Jasen Dec 23 '16 at 21:09
  • @TheDude Are you asking about MVC 5 or MVC Core ?? – Lukasz Mk Dec 23 '16 at 23:20

1 Answers1

7

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:

Lukasz Mk
  • 7,000
  • 2
  • 27
  • 41