1

I'm building a CRUD that is accessible only to logged in users and i'm trying to add extra information (userid) to the crud records. How do I go about fetching the userId and saving it with the record?

Here is my controller

public ActionResult Create()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CompanyName,Telephone")]Company company)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Companies.Add(company);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException /* dex */)
    {

        ModelState.AddModelError("", "Unable to save changes.");
    }

    return View(company);
}

Here is my model

namespace ProjectX.Models
{
    public class Company
    {
        //public int Id { get; set; }
        public int CompanyID { get; set; }
        public string CompanyName { get; set; }
        public string Telephone { get; set; }

    }
}

Thank you for your help!

Anastasios Selmani
  • 3,579
  • 3
  • 32
  • 48
papapi
  • 61
  • 9

1 Answers1

1

You can access it in different ways depending where you are in the code but since you are in the controller you should have an extension method like this User.Identity.GetUserId(); It will be string in this case but you can parse it, but be sure your table AspNetUsers has the id as int datatype. Assuming this is true you can say:

[HttpPost, Authorize]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CompanyName,Telephone")]Company company)
{
    try
    {
        if (ModelState.IsValid)
        {
            company.Id = int.Parse(User.Identity.GetUserId());
            db.Companies.Add(company);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException /* dex */)
    {
        ModelState.AddModelError("", "Unable to save changes.");
    }

    return View(company);
}

Do not forget to apply [Authorize] attribute.

In case you want to save more data from a user to a Company then you need to get the user from database and then extract user`s data needed from it and then save them in company object like below:

var user = UserManager.FindById(int.Parse(User.Identity.GetUserId()));
company.Username = user.Username;
//and so on...

Here you have more details for this:

Rey
  • 3,663
  • 3
  • 32
  • 55