Asp.net-Mvc-4

在 MVC 4 中創建下拉列表的最佳方法是什麼?

  • December 9, 2013

我想知道,在 MVC 4 中創建下拉列表的最佳方法是什麼?使用ViewBag還是其他方法?

我會爭辯說,由於這些項目是您視圖中的變數值,因此它們屬於視圖模型。視圖模型不一定只用於視圖返回的項目。

模型:

public class SomethingModel
{
   public IEnumerable<SelectListItem> DropDownItems { get; set; }
   public String MySelection { get; set; }

   public SomethingModel()
   {
       DropDownItems = new List<SelectListItem>();
   }
}

控制器:

public ActionResult DoSomething()
{
   var model = new SomethingModel();        
   model.DropDownItems.Add(new SelectListItem { Text = "MyText", Value = "1" });
   return View(model)
}

看法:

@Html.DropDownListFor(m => m.MySelection, Model.DropDownItems)

在控制器或適合該場景的其他任何地方填充它。

或者,為了獲得更大的靈活性,請切換並執行以下操作public IEnumerable<SelectListItem>public IEnumerable<MyCustomClass>

@Html.DropDownFor(m => m.MySelection,
   new SelectList(Model.DropDownItems, "KeyProperty", "ValueProperty")

在這種情況下,您當然還必須修改控制器操作以填充model.DropDownItemsof 的實例MyCustomClass

引用自:https://stackoverflow.com/questions/16118175