1.4.4.Model binding and save data
1.Add submit button to the form
@using (Html.BeginForm("Create", "Customers"))
{
<button type="submit" class="btn btn-primary">Save</button>
}
2.Create a Http POST action
[HttpPost]
public ActionResult Save(Customer customer)
{
if (customer.Id == 0)
{
_context.Customers.Add(customer);
}
else
{
var customersInDb = _context.Customers.Single(c => c.Id == customer.Id);
//Not recommand
//TryUpdateModel(customersInDb, "", new string[] {"Name", "Email"});
customersInDb.Name = customer.Name;
customersInDb.Birthday = customer.Birthday;
customersInDb.membershipTypeId = customer.membershipTypeId;
customersInDb.IsSubscribeToNesletter = customer.IsSubscribeToNesletter;
}
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
Last updated