当我从下拉列表中选择类别时,它不会保存在数据库中。在数据库中,它显示101所有值
我的view.cshtml是
<h4>RecStock</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="editor-field">
@Html.DropDownList("Category",null, new { @class = "form-control" } )
</div>
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
</div>
</div>
我的控制器
public ActionResult Create()
{
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Category,ProductName,ReceiveQty,Date")] RecStock recStock)
{
if (ModelState.IsValid)
{
db.RecStocks.Add(recStock);
ViewBag.Category = new SelectList(db.ProductDetails, "id", "Category", recStock.id);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(recStock);
}
答案 0 :(得分:0)
你应该使用&#34; DropDownListFor&#34;并将选定的下拉值分配给相应的模型属性,如下所示:
@Html.DropDownListFor(m => m.MyModelProperty, new SelectList(Model.ListOfStuff, "ListOfStuffId", "ListOfStuffName"), string.Empty, new {@class = "form-control", id = "myList"})