c# - 发布项目时在 ASP.NET C# 中获取用户 ID

标签 c# .net e-commerce identity

我正在为我的本地社区构建一个小型的 craigslist/ebay 类型的市场。

大部分站点都是简单的增删改查操作。我启用了个人用户帐户,当有人向市场发布商品时,我想将他们当前的用户 ID 绑定(bind)到该帖子。我设置了字段,但如何自动附加登录用户的 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 字符串值,但我不知道如何设置它。

这是我创建的产品 Controller 。我会在这里输入那个 userID 逻辑吗?

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

最佳答案

是的,您需要在保存之前将用户添加到产品中。像这样的东西:

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

我有一段时间没有使用实体,所以我认为这应该是正确的

关于c# - 发布项目时在 ASP.NET C# 中获取用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29970286/

相关文章:

c# - 从 Tuple.ToString() 返回的字符串中获取元组

c# - 从字符串中获取特定的单词c#

c# - 将 Kinect 的 v2.0 运动存储到 BVH 文件

c# - 为什么有时 2 个对象引用相同但不总是

c# - 更改 WCF 引用 URL .Net Core

mySql - 为批量采购建模价格折扣表的最佳方式 - 递归?

mysql - Spree 2.0.0 在结帐时合并 2 个州?

c# - Entity Framework Code First 多对多创建重复行

c# - 从前置摄像头捕获的图像旋转 - Windows Phone 8

php - 根据选项组和选项计算产品变体