how to edit objects with other ie IList<object> or simple object attached to it?
Hi Im stuck on how to do this the best way. In my case I got a Product and it got a Manufacturer Object.
So what I do is I pass the product to the view to edit. But when I do the save I look at the product object and Manufacturer is now null. I tried to do a hiddenfor for the Manufacturer Object like I do with id for the product, but that wont work. How is the best way to do this?
hope you get what I mean?
public ActionResult EditProduct(int id)
{
var product = _productService.GetById(id);
return View(product);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditProduct(Product product)
{
//_productService.SaveOrUpdate(product);
TempData[Message] = product.ProductName + " have been saved";
return RedirectToAction("Products");
}
EDIT
Product Object
public virtual int Id { get开发者_如何学JAVA; set; }
public virtual string ProductName { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
From what you say, I think the problem is the context in which you try to save your Product. When you declare it as
public ActionResult EditProduct(Product product)
it doesn't have the same "meaning" as
var product = _productService.GetById(id);
Because it lacks your database context. So I suggest you to do the following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditProduct(int id)
{
var product = _productService.GetById(id);
UpdateModel(product);
_productService.SaveOrUpdate(product);
TempData[Message] = product.ProductName + " have been saved";
return RedirectToAction("Products");
}
try this in your View
put a hidden field for the Manufacturer.Id
if this is your Manufacturer's primary key
<%=Html.HiddenFor(m=>m.Manufacturer.Id, new { @value=Model.Manufacturer.Id }) %>
this will give you a value for your Manufacturer Object in your Product. Now you just have to rebind your Manufacturer before you save it since you have your Manufacturer's primary key.
精彩评论