3

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

Most of the site is simple CRUD operations. I have enabled Individual user accounts and when someone posts an item to the marketplace I'd like to bind their current userID to the post. I have the fields set up but how can I automatically attach the logged in user's 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 hold the ApplicationUser_Id string value, but I do not know how to set it.

This is my create product controller. Would I put in that 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);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Seth Johnson
  • 135
  • 1
  • 1
  • 11

1 Answers1

0

Yes, you would 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 awhile, so I think this should be correct

Seth T
  • 305
  • 1
  • 10
  • Thank you for you help. In this instance how would db.Products.ApplicationUser = currentUser pass the UserID value into my products table? – Seth Johnson Apr 30 '15 at 14:58
  • currentUser would be type ApplicationUser, which should have the user id set. do you have code already to retreive your user? you are then linking the user object to the product in the controller(above code). trying to remember if you need more in the POCO – Seth T Apr 30 '15 at 15:18
  • I do not have the code set to retrieve my user yet. – Seth Johnson Apr 30 '15 at 15:21
  • All I have set up is the CRUD scaffolding. so on the create page I have the inputs mapped to the DB, but I need to bind the current users ID to that form (hidden) and pass it to the products table – Seth Johnson Apr 30 '15 at 15:23
  • You shouldn't put the id in the form, hidden field values can be changed. It should be pulled in the controller like User.Identity.GetUserId(); Check out http://stackoverflow.com/questions/18448637/how-to-get-current-user-and-how-to-use-user-class-in-mvc5 – Seth T Apr 30 '15 at 15:30