我有一個Product
模型已創建,並希望從Tax
模型中爲產品添加相關稅。單個產品可以應用多種稅收,因此我創建了另一個型號TaxApplied
來存儲關係。MVC 4綁定到子表的列表
我已將ListBox
與MultiSelectList
添加到Product
的創建視圖,該視圖顯示可用稅。
@Html.ListBox("AppliedTaxes", ViewBag.AppliedTaxes as MultiSelectList)
但是,當我嘗試使用選定稅款創建產品時,出現以下錯誤。我應該如何修改視圖,模型或控制器以添加稅收關係?
The ViewData item that has the key 'AppliedTaxes' is of type 'System.Collections.Generic.List`1[[StoreManager.Models.TaxApplied, StoreManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' but must be of type 'IEnumerable<SelectListItem>'.
模型下面描述
public class Product
{
public int ID { get; set; }
public string Name { get; set;
public float SalePrice { get; set; }
public List<TaxApplied> AppliedTaxes { get; set; }
}
public class Tax
{
public int ID { get; set; }
[DisplayName("Tax Code")]
public string TaxCode { get; set; }
[DisplayName("Tax Percent")]
public string Value { get; set; }
}
public class TaxApplied
{
public int ID { get; set; }
[ForeignKey("Product")]
public int ProductID { get; set; }
[ForeignKey("Tax")]
public int TaxID { get; set; }
public virtual Product Product { get; set; }
public virtual Tax Tax { get; set; }
}
控制器的動作爲Product
創建
//
// GET: /Product/Create
public ActionResult Create()
{
ViewBag.NavProduct = "active";
MultiSelectList taxes = new MultiSelectList(db.Taxes.ToList<Tax>(), "ID", "Name");
ViewBag.AppliedTaxes = taxes;
return View();
}
//
// POST: /Product/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Product product)
{
ViewBag.NavProduct = "active";
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
看一看變量類型Html.ListBox。它期望一個List,並且您似乎將它傳遞給List 。嘗試Html.ListBox(「AppliedTaxes,新的SelectList((IList )ViewBag.Taxes,...)) –
David
我修改了視圖的控制器,表單顯示得很好,它是提交給我的表單錯誤 MultiSelectList taxes = new MultiSelectList(db.Taxes.ToList(),「ID」,「Name」); ViewBag.AppliedTaxes = taxes; –