Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何传递用户';将屏幕名称添加到视图中_Asp.net Mvc_Openid_Dotnetopenauth - Fatal编程技术网

Asp.net mvc 如何传递用户';将屏幕名称添加到视图中

Asp.net mvc 如何传递用户';将屏幕名称添加到视图中,asp.net-mvc,openid,dotnetopenauth,Asp.net Mvc,Openid,Dotnetopenauth,我想在母版页中包含的局部视图中显示用户的屏幕名称。这是经典的“登录”/“欢迎John Smith!注销”场景。用户的屏幕名称不同于user.Identity.name,需要进行数据库查找,即 AppUser currentUser = appRepository.GetAppUser(User.Identity.Name); string screenName = currentUser.ScreenName; 这在视图中是行不通的——没有对“appRepository”的引用,视图也不应该真

我想在母版页中包含的局部视图中显示用户的屏幕名称。这是经典的“登录”/“欢迎John Smith!注销”场景。用户的屏幕名称不同于
user.Identity.name
,需要进行数据库查找,即

AppUser currentUser = appRepository.GetAppUser(User.Identity.Name);
string screenName = currentUser.ScreenName;
这在视图中是行不通的——没有对“appRepository”的引用,视图也不应该真的到处调用数据库。我应该如何设置,以便将屏幕名称从控制器传递到视图

我的所有控制器都继承自
BaseController
。我尝试在
BaseController
类的构造函数中设置
ViewData[“CurrentAppUser.ScreenName”]
,但此时用户对象尚未填充。(如果相关的话,我将OpenID与DotNetOpenAuth一起使用。)我可以在每个控制器上的每个操作方法中设置它,但那将非常难看

我还尝试在用户登录时设置会话变量,但似乎即使会话结束,用户也可以保持登录状态。当他们再次返回时,他们仍然登录,但会话变量未设置


有什么想法吗?

我建议您使用。因此,您通常从定义视图模型开始:

public class UserInfoViewModel
{
    public string ScreenName { get; set; }
}
然后控制器:

public class UserInfoController: Controller
{
    private readonly IUsersRepository _repository;
    public UserInfoController(IUsersRepository repository)
    {
        _repository = repository;
    }

    // Use this attribute if you want to restrict direct access
    // to this action.
    [ChilActionOnly] 
    public ActionResult Index()
    {
        var model = _repository.GetUserInfo(User.Identity.Name);
        return PartialView(model);
    }
}
相应的局部视图:

@model UserInfoViewModel
<div>Hello @Html.DisplayFor(x => x.ScreenName )</div>
或者(
Html.RenderPartial
执行相同的操作,但不返回结果,而是将其直接写入输出流):

为了避免在每次请求获取用户屏幕名称时命中数据库,进一步的改进是将其缓存在某个位置:会话、cookie


因此不需要基本控制器和
ViewData
。获取用户屏幕名称的逻辑与主MVC管道完全分离,并作为小部件嵌入

太棒了,非常感谢。也感谢Haack链接。
@Html.Action("Index", "UserInfo")
@{Html.ActionPartial("Index", "UserInfo");}