我想使用dropdownList与modelId和categoryId两个外键。 我正在使用ViewBag和selectList。ViewBag多个SelectList下拉列表
public ActionResult Create()
{
ViewBag.categoryId = new SelectList(db.Category, "categoryId", "name");
ViewBag.modelId = new SelectList(db.Model, "modelId", "name");
return View();
}
//
// POST: /Product/Create
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
db.Product.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.categoryId = new SelectList(db.Category, "categoryId", "name", product.categoryId);
ViewBag.modelId = new SelectList(db.Model, "modelId", "name", product.modelId);
return View(product);
}
这里是我的Create.cshtml。
<div class="editor-label">
@Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
@Html.DropDownList("categoryId", "--Select--")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.DropDownList("modelId", "--Select--")
</div>
当我按下提交按钮,错误上来, “具有相同键的项已被添加” 是什么问题呢?在模型中有问题吗?
这是我的模特。
--Prodruct.cs--
public class Product
{
[Key] public int productId { get; set; }
[Required(ErrorMessage = "Please select category")]
public int categoryId { get; set; }
[Required(ErrorMessage = "Please select model")]
public int modelId { get; set; }
[DisplayName("Model name")]
public String model { get; set; }
public virtual Category Category { get; set; }
public virtual Model Model { get; set; }
}
--Category.cs--
public class Category
{
[Key] public int categoryId { get; set; }
public String name { get; set; }
}
--Model.cs--
public class Model
{
[Key] public int modelId { get; set; }
public String name { get; set; }
}
--RentalDB.cs--
public class rentalDB : DbContext
{
public DbSet<Product> Product { get; set; }
public DbSet<Model> Model { get; set; }
public DbSet<Customer> Customer { get; set; }
public DbSet<Order> Order { get; set; }
public DbSet<Cart> Cart { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<OrderDetails> OrderDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
哪里出错了?创建中的索引页面可以获取类别数据和模型数据。但是,当我提交时,它有错误,'已添加具有相同密钥的项目'。 你能帮我解决问题吗? 谢谢。
- 添加更多编码 -
我正在使用此LINQ。可能这里有问题。
如何在此处添加“模型”实体?
var product = from a in db.Product.Include(a => a.Category)
select a;
我加了一个关于如何完成的详细答案。 – 2012-04-06 13:24:55