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

Using MVC dropdown list how to edit form and show the data in dropdown and previously selected item in dropdown?

我正在使用 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 来完成 this.you 只需在 document.ready(function()

中编写您的 javascript 代码

document.getElementById("your dropdown id").value = '@Model.yourDropdownValue';