ZKF3340320
ZKF3340320

Reputation: 181

How to get logged UserID in asp.net MVC and display it in hidden text box

I can get username using @user.identity.name from table user but i need to get UserID instead of Username. how to do it?. i tried the following code in my controller but it returns 0.

My Controller:

public ActionResult Index()
    {
        int userId = User.Identity.GetUserId<int>();
        User currentUser = db.Users.FirstOrDefault(x => x.UserID == userId);
        ViewBag.UID=userId;
        return View();
    }

My View

 <input value="@ViewBag.UID" type="hidden"/>

My Model

[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; }


}

Upvotes: 1

Views: 1176

Answers (2)

AT-2017
AT-2017

Reputation: 3149

If this isn't about ASP.NET membership, then you should be using your own method and query to do so as follows: (I guess, you are passing email for the login)

int currentUser = db.Users.Where(x => x.Email == email).Select(x => x.userId);
ViewBag.UID = Convert.ToInt32(userId);

Upvotes: 1

Bharat
Bharat

Reputation: 2464

It should return UserIdid

string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

Upvotes: 0

Related Questions