Uzair Nadeem
Uzair Nadeem

Reputation: 745

How do I get the user ID in any class in MVC?

I am retrieving a list of communities from search. I want to add a button for Join if the current user has not joined the community or Leave if the current user has already joined that community. I have created isMember() function as

public bool IsMember(string UserID, int CommunityID)
{
    var Membership = db.Users.Include(x => x.CommunityUsers)
                             .Where(s => s.Id.Equals(UserID))
                             .Count();

    if (Membership > 0)
        return true;
    else
        return false;
}

but how can I use this in my search function? I need to pass current UserID in this function but I am unable to do this. Here is my search function.

public ActionResult SearchCommunity(string searchString)
{
    if (!String.IsNullOrEmpty(searchString))
    {
        var UseriD = db.Users.Where(u => u.UserName == User.Identity.Name)
                             .Select(u => u.Id);

        ViewBag.communityQuery = db.Communities.Include(x => x.CommunityUsers)
                                        .Where(s => s.CommunityName.Contains(searchString))
                                        .ToList();
        ViewBag.Membership = IsMember(UseriD, ViewBag.communityQuery).ToList();

        return View();
    }

Upvotes: 0

Views: 1466

Answers (3)

Christian Gollhardt
Christian Gollhardt

Reputation: 17004

You first need to obtain the current http context and then you can get the user:

var ctx = HttpContext.Current;
ctx.User.Identity.GetUserId();

If you are in an MvcController, you can use the User property:

User.Identity.GetUserId();

Upvotes: 0

Md Afjal
Md Afjal

Reputation: 16

You can try this code:

var userId=User.Identity.GetUserId();

Upvotes: 0

Roman Chichin
Roman Chichin

Reputation: 36

This code will return you an IEnumerable:

var UseriD = db.Users.Where(u => u.UserName == User.Identity.Name)
                     .Select(u => u.Id);

Try to use:

var UseriD = db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

Upvotes: 2

Related Questions