开发者

Use viewBag in Master page Asp.net MVC

开发者 https://www.devze.com 2023-03-09 05:59 出处:网络
I am developing a website using asp.net MVC I want to show the name of user after he/she logged in the website.

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 no开发者_Python百科t know where to define it.

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

Should I use filter?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消