我对ASP.net还是陌生的,我正在尝试使用MVC。我有一种使用Linq从sql数据库获取当前用户信息的方法。我如何将这些结果输入视图并在网站的任何地方使用它们?
我获取用户信息的方法:
public List<AspNetUser> GetCurrentUser()
{
FulfillmentContext db = new FulfillmentContext();
string username = HttpContext.Current.User.Identity.GetUserName();
var currentUser = (from u in db.AspNetUsers
join ur in db.AspNetUserRoles on u.Id equals ur.UserId
join r in db.AspNetRoles on ur.RoleId equals r.Id
where u.UserName == username
select u).ToList();
return currentUser;
}
答案 0 :(得分:1)
理想情况下,您应该将其加载到模型中
public ActionResult Index()
{
FulfillmentContext db = new FulfillmentContext();
string username =
HttpContext.Current.User.Identity.GetUserName();
var currentUser = (from u in db.AspNetUsers
join ur in db.AspNetUserRoles on u.Id equals ur.UserId
join r in db.AspNetRoles on ur.RoleId equals r.Id
where u.UserName == username
select u).First();
var model = new Model();
model.CurrentUser = currentUser;
return View(model);
}
但是,您可以创建HTML帮助程序扩展名:
public static AspNetUser GetCurrentUser(this HtmlHelper helper)
{
FulfillmentContext db = new FulfillmentContext();
string username = HttpContext.Current.User.Identity.GetUserName();
var currentUser = (from u in db.AspNetUsers
join ur in db.AspNetUserRoles on u.Id equals ur.UserId
join r in db.AspNetRoles on ur.RoleId equals r.Id
where u.UserName == username
select u).First();
return currentUser;
}
然后从您的视图中调用它:
@{
var user = Html.GetCurrentUser();
}