编辑(获取):
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.Products = new MultiSelectList(db.Products.Where(p => p.Type == Type.Eletronic && p.Id != product.Id), "Id", "Name", product.SimilarProducts.Select(p => p.Id)); // Here my SimilarProducts.Count is 2
return View(product);
}
编辑(发布):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Price,Type,Quantity,DeptId")] Product product)
{
if (ModelState.IsValid)
{
var similars = product.SimilarProducts; // Here I get count = 0, why?
...
}
ViewBag.Products = new MultiSelectList(db.Products.Where(p => p.Type == Type.Eletronic && p.Id != product.Id), "Id", "Name", product.SimilarProducts.Select(p => p.Id));
return View(product);
}
生成的html:
<select class="form-control" id="Products" multiple="" name="Products" size="5">
<option selected="selected" value="2">Headphone</option>
<option selected="selected" value="3">Smartphone</option>
<option value="4">Cell</option>
<option value="6">Notebook</option>
<option value="7">Desktop</option>
</select>
嗯,问题是:在我的ActionResult(GET)“编辑”中,类似产品的数量是2(什么是正确的),当它发布时,我做了一些更改后(我添加了更多1个相似的产品,所以它应该是3),计数变为0,为什么?这是EF的问题吗?