I am new to .NET MVC (Learning). I have the following method in Controller(this is not clean code and I am learning)
[HttpPost]
public ActionResult Edit(ProductCategoryLocation viewModel)
{
if (ModelState.IsValid)
{
var product = viewModel.Product;
product.Category = db.Categories
.Where(c => c.ID == viewModel.CategoryID).Single();
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
The View Model Has Product, Location and Category Types and CategoryID and LocationID. In the POST method I am getting the category ID from the View Model, Update the Category of the Product and then Update the Model to the Database. Any changes to the properties of Products gets saved except the manually changed Category.
Is there a mistake / Am I missing something?
Is this the right way of doing update using View Model?
You can directly assign
CategoryIDof the view model toCategoryIDof the product. This way you do not have to retrieve the category from the database.If you do not have a scalar property
CatagoryIDyou have to define it in theProductclass