将AD用户名传递到MVC中的视图中
本文关键字:MVC 视图 AD 用户 | 更新日期: 2023-09-27 18:24:30
我可以使用System.DirectoryServices.ActiveDirectory.从AD获取用户信息
我也可以获得用户名没有域名如下所示。我的问题是如何将这些信息传递给我的视图?
DirectoryContextMock directorycontent = new DirectoryContextMock();
System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity = user.Identity;
string a= identity.Name.Substring(identity.Name.IndexOf(@"'") + 1);
目前,我的视图中有以下代码,它很有效,但我想将"a"而不是@User.Identity.Name传递到该视图中。这似乎很容易做到,但我无法做到。
Hello, <span class="username">@User.Identity.Name</span>!
在上面的评论中,您说a
正在您的控制器中定义。因此,您有几个非常简单的选项可以将数据发送到您的视图:
1) 在模型上创建一个属性,并将a
的值存储在该属性上。
2) 将其添加到ViewBag
,例如:
// in the controller action
ViewBag.Username = a;
// in the view
@ViewBag.Username
您也可以使用类似于ViewBag
的其他临时存储机制,如TempData
或ViewData
。(ViewData
和ViewBag
的用途非常相似,后者在后来的版本中被添加到框架中。)
只需将要传递到视图中的属性添加到模型中。
如果不使用模型,则可以使用ViewBag
动态特性。
public class MyModel
{
public string Identity {get;set;}
}
public class MyController : BaseController
{
public ActionResult Get()
{
var myModel = new MyModel();
myModel.Identity = System.Web.HttpContext.Current.User.Identity.Name;
//snip
return View(myModel);
}
}