title: How do I get the user ID in any class in MVC?
body: <p>I am retrieving a list of communities from search. I want to add a button for <strong>Join</strong> if the current user has not joined the community or <strong>Leave</strong> if the current user has already joined that community. I have created <code>isMember()</code> function as</p>
  
  <pre><code>public bool IsMember(string UserID, int CommunityID)
  {
      var Membership = db.Users.Include(x =&gt; x.CommunityUsers)
                               .Where(s =&gt; s.Id.Equals(UserID))
                               .Count();
  
      if (Membership &gt; 0)
          return true;
      else
          return false;
  }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>public ActionResult SearchCommunity(string searchString)
  {
      if (!String.IsNullOrEmpty(searchString))
      {
          var UseriD = db.Users.Where(u =&gt; u.UserName == User.Identity.Name)
                               .Select(u =&gt; u.Id);
  
          ViewBag.communityQuery = db.Communities.Include(x =&gt; x.CommunityUsers)
                                          .Where(s =&gt; s.CommunityName.Contains(searchString))
                                          .ToList();
          ViewBag.Membership = IsMember(UseriD, ViewBag.communityQuery).ToList();
  
          return View();
      }
  </code></pre>