我可以从表用户使用@ user.identity.name获取用户名,但我需要获取UserID而不是Username。怎么做?。我在我的控制器中尝试了以下代码,但它返回0.
我的控制器:
public ActionResult Index()
{
int userId = User.Identity.GetUserId<int>();
User currentUser = db.Users.FirstOrDefault(x => x.UserID == userId);
ViewBag.UID=userId;
return View();
}
我的观点
<input value="@ViewBag.UID" type="hidden"/>
我的模特
[Table("User")]
public partial class User
{
public int UserID { get; set; }
//added by zakerr
public int? DepartmentID { get; set; }
public string Firstname{ get; set; }
public string Lastname { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength =4)]
[DataType(DataType.Password)]
public string Password { get; set; }
public string UserEmailAddress { get; set; }
[StringLength(50)]
public string Status { get; set; }
}
答案 0 :(得分:1)
如果这不是关于ASP.NET成员资格,那么您应该使用自己的方法和查询,如下所示:(我想,您正在通过电子邮件进行登录)
int currentUser = db.Users.Where(x => x.Email == email).Select(x => x.userId);
ViewBag.UID = Convert.ToInt32(userId);
答案 1 :(得分:0)
它应该返回UserIdid
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);