Home > Mobile >  In a create view, insert data at the same time to two different table in ASP.NET MVC?
In a create view, insert data at the same time to two different table in ASP.NET MVC?

Time:12-10

I'm doing an ASP.NET MVC project and I'm having trouble to make the create view work: it doesn't save data into two tables. I'm creating a client with name, email, address, zipcode city.

These are my two tables:

Clients table:

    public int ClientID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public Nullable<int> MailID { get; set; }
    public virtual PostOffices PostOffices { get; set; }

And then I have PostOffices table:

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public PostOffices()
    {
        this.Clients = new HashSet<Clients>();
    }

    public int MailID { get; set; }
    public string Zipcode { get; set; }
    public string City { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Clients> Clients { get; set; }

I have written a controller looking like this:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ClientID,Name,Email,Address,MailID")] Clients clients)
    {
        if (ModelState.IsValid)
        {
            db.Asiakkaat.Add(asiakkaat);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(asiakkaat);
    }

In the view it shows everything and lets me enter data into all of the input boxes, but it only saves data to the Clients table like name, email, address, but it doesn't save anything into the PostOffices table (meaning zipcode and city).

Is there something wrong with my controller? Or should I somehow add into a client class a zipcode city, and not the MailID? I can't get it to work.

I appreciate the help!

CodePudding user response:

Just remove [Bind] and never use this attribute in the future

 public ActionResult Create( Clients clients)
  • Related