2015-04-30 85 views
3

我正在爲當地社區構建一個小型的craigslist/ebay類型的市場。在發佈項目時在ASP.NET C#中獲取用戶標識

大多數網站都是簡單的CRUD操作。我已啓用個人用戶帳戶,當某人將商品發佈到市場時,我想將其當前用戶ID綁定到該帖子。我設置了字段,但我如何自動附加登錄用戶的ID。

這是我的產品,一流的

public class Product 
{ 
    public string Title { get; set; } 
    public decimal Price { get; set; } 
    public string Photo { get; set; } 
    public string Description { get; set; } 
    public bool Availability { get; set; } 
    public string Category { get; set; } 

    public string Id { get; set; } 

    public virtual ApplicationUser ApplicationUser { get; set; } 
} 

我在產品數據庫表中的字段,將持有的ApplicationUser_Id字符串值,但我不知道如何設置它。

這是我創建產品控制器。我會在這裏放入該用戶ID邏輯嗎?

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include = "Id,Title,Price,Description,Availability,Category,Photo")] Product product) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Products.Add(product); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(product); 
} 

回答

0

是的,您需要在保存之前將用戶添加到產品中。喜歡的東西:

if (ModelState.IsValid) 
{ 
    db.Products.Add(product);   
    db.Products.ApplicationUser = currentUser; //depending how you have your user defined  
    db.SaveChanges(); 
    return RedirectToAction("Index"); 
} 

我沒有用實體在一段時間,所以我覺得這應該是正確的

+0

謝謝你的幫助。在這種情況下,db.Products.ApplicationUser = currentUser如何將UserID值傳遞到我的產品表中? –

+0

currentUser將是類型ApplicationUser,它應該設置用戶標識。你是否有代碼來檢索你的用戶?您然後將用戶對象鏈接到控制器中的產品(上面的代碼)。試圖記住,如果你需要更多的POCO –

+0

我沒有設置檢索我的用戶的代碼。 –

相關問題