2017-04-10 39 views
0

我從搜索中檢索社區列表。我想爲添加一個按鈕如果當前用戶還沒有加入社區,或者離開,如果當前用戶已加入該社區,請加入。我創建isMember()功能如何在MVC中的任何類中獲取用戶標識?

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

,但我怎麼能在我的搜索功能使用?我需要在這個函數中傳遞當前用戶標識,但我無法做到這一點。這是我的搜索功能。

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(); 
    } 
+0

看我怎麼刪除了你的代碼中過多的空白,並使其更容易閱讀?請在將來發布代碼時這樣做。可讀性很重要,並使您更有可能收到一個很好的答案。 – mason

+0

您是否在用戶登錄後在會話中保留用戶ID? – Krishna

回答

1

此代碼將返回一個IEnumerable:

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

嘗試使用:

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

你可以試試這個代碼:

var userId=User.Identity.GetUserId(); 
0

首先,您需要獲取當前的http上下文,然後你就可以獲得用戶:

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

如果你是在MvcController,您可以使用User屬性:

User.Identity.GetUserId(); 
相關問題