我正在使用MVC4并在下拉列表中显示类别。泡沫允许用户编辑先前添加的数据。因此,当我执行更新操作时,用户输入的所有其他数据都可以轻松显示,但是谁可以从下拉列表中显示选定的类别值并在下拉列表中显示该阀门?
控制器
using (var catRepo = new BusinessLayer.Repostories.CategoryRepository())
{
ViewBag.VBCategoryList = new SelectList(catRepo.GetAllCategories(),"CategoryId","Name");
}
视图
@Html.DropDownList("CategoryId", ViewBag.VBCategoryList as SelectList)
您的模型应包含 CategoryId
public int CategoryId{get;set;}
您的编辑操作将类似于以下代码
public ActionResult Edit(int id)
{
using (var catRepo = new BusinessLayer.Repostories.CategoryRepository())
{
var itemToEdit=catRep.GetItemById(id);// replace your method
ViewBag.VBCategoryList = new SelectList(catRepo.GetAllCategories(),"CategoryId","Name",itemToEdit.CategoryId);
}
return View(itemEdit);
}
你也可以
使用JavaScript来做到这一点.你只需在document.ready(function()
document.getElementById("your dropdown id").value = '@Model.yourDropdownValue';