【问题标题】:Getting userID in ASP.NET C# when posting item发布项目时在 ASP.NET C# 中获取用户 ID
【发布时间】:2015-07-10 07:21:06
【问题描述】:

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

大部分网站都是简单的 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);
}

【问题讨论】:

    标签: c# .net e-commerce identity


    【解决方案1】:

    是的,您需要先将用户添加到产品中,然后才能保存。比如:

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

    我有一段时间没用过Entity了,所以我觉得应该是对的

    【讨论】:

    • 感谢您的帮助。在这种情况下,db.Products.ApplicationUser = currentUser 如何将 UserID 值传递到我的产品表中?
    • currentUser 将是 ApplicationUser 类型,它应该设置用户 ID。您是否已经有代码来检索您的用户?然后,您将用户对象链接到控制器中的产品(上面的代码)。试图记住你是否在 POCO 中需要更多
    • 我还没有设置代码来检索我的用户。
    • 我只设置了 CRUD 脚手架。所以在创建页面上,我将输入映射到数据库,但我需要将当前用户 ID 绑定到该表单(隐藏)并将其传递给产品表
    • 你不应该把id放在表单中,隐藏字段值可以更改。它应该像 User.Identity.GetUserId(); 一样被拉入控制器;查看stackoverflow.com/questions/18448637/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    相关资源
    最近更新 更多