使用MVC下拉列表如何编辑表单并在下拉列表中显示数据以及下拉列表中先前选择的项目?

时间:2015-03-09 03:41:14

标签: asp.net-mvc asp.net-mvc-4

我正在使用MVC4并在下拉列表中显示类别。泡沫允许用户编辑以前添加的数据。因此,当我执行更新操作时,用户输入的所有其他数据都可以轻松显示,但是谁从下拉列表中显示所选类别值并显示该阀门是否下拉?

控制器

using (var catRepo = new BusinessLayer.Repostories.CategoryRepository())
{
  ViewBag.VBCategoryList = new SelectList(catRepo.GetAllCategories(),"CategoryId","Name");
}

查看

 @Html.DropDownList("CategoryId", ViewBag.VBCategoryList as SelectList)

2 个答案:

答案 0 :(得分:0)

您的模型应包含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);
} 

答案 1 :(得分:0)

您也可以使用javascript来执行此操作。您只需在document.ready(function()

中编写您的javascript代码

document.getElementById(“your dropdown id”)。value ='@ Model.yourDropdownValue';