在视图中创建我想要添加新产品。我需要从下拉列表中选择类别名称。问题是,我在表格中只添加了类别ID。以及我如何添加和命名类别?
构建我的数据库:
表品牌:idbrand,名称。
表格制作:idbrand,namebrand,idmake,name,price,urlmake。
我执行以下操作:
// GET: /ShopManager/Create
public ActionResult Create()
{
ViewBag.BrandID = new SelectList(db.Brand, "BrandID", "Name");
return View();
}
//
// POST: /ShopManager/Create
[HttpPost]
public ActionResult Create(Make make)
{
if (ModelState.IsValid)
{
db.Make.AddObject(make);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.BrandID = new SelectList(db.Brand, "BrandID", "Name", make.BrandID);
return View(make);
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Марка телефона</legend>
<div class="editor-label">
@Html.LabelFor(model => model.BrandID, "Бренд")
</div>
<div class="editor-field">
@Html.DropDownList("BrandID", String.Empty)
@Html.ValidationMessageFor(model => model.BrandID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name, "Марка телефона")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Price, "Цена")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.UrlMake, "Изображение")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UrlMake)
@Html.ValidationMessageFor(model => model.UrlMake)
</div>
<p>
<input type="submit" value="Создать" />
</p>
</fieldset>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我如何在表中添加品牌ID和品牌名称(类别名称)?
答案 0 :(得分:1)
由于您拥有品牌表,因此无需在Make中存储品牌名称,您可以通过简单的连接获得。无论如何,如果您真的想在创建中执行此操作,您可以将其设置为以下代码
make.NameBrand = db.Brand.Where(b => b.idbrand == make.idbrand).SingleOrDefault().namebrand;