1

I am developing a website using asp.net MVC

I want to show the name of user after he/she logged in the website.

The problem is that User.Identity.Name returns user email and I do not want to change that because user name is not unique. And I want to access email in other pages.

I like to use a viewBag in my master page, but I do not know where to define it.

If I define it in Home/controller, it works just for this action.

Should I use filter?

tereško
  • 58,060
  • 25
  • 98
  • 150
Elham
  • 777
  • 1
  • 11
  • 23

2 Answers2

1

This link will help you with the problem of passing data to master page.

This is the "official" way to handle that, it explains in a very clear way, but I strongly recommend to read the first link completly too.

Community
  • 1
  • 1
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
1

If you're using MVC, then I would strongly suggest moving to a ViewModel pattern to accomplish this, rather than stuffing objects into the ViewBag, mostly for two reasons: 1) Type Safety, and 2) Intellisense support.

In this kind of situation, you would have your MasterPage inherit from a BaseViewModel, and your actions would return derived objects from the BaseViewModel. You can then set data on your view model, and it will be available to the master page when rendering:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<MyViewModelBase>" %>

Alternatively, you could make a 'partial view' that renders just the content you need based on the user's state.

Tejs
  • 40,736
  • 10
  • 68
  • 86