Getting user id in ASP.NET C # when submitting an item

I am building a small Craigslist / ebay marketplace for my local community.

Most of the site is simple CRUD operations. I have enabled separate user accounts and when someone submits an item to the marketplace, I would bind their current user ID to the post. I have the fields set, but how can I automatically attach the registered user id.

This is my product class

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

      

I have a field in the product database table that will contain a string value ApplicationUser_Id

, but I don't know how to set it.

This is my product controller. Would I include userID logic here?

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

      

+3


source to share


1 answer


Yes, you will need to add the user to the product before you save it. Something like:

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

      



I haven't used Entity in a while, so I believe this should be correct

0


source







All Articles