我正在做一個MVC APP。對于這個例子..
在我對我的定義中,我DropDownListFor定義了這樣的東西。
@Html.DropDownListFor(model => model.SelectedSystem, Model.Systems, new { @class = "form-control listbox",id="Origin" })
我的模型加載在控制器中,它Model.System在某些情況下加載。Model.System 是型別List<SelectListItem>
選擇的選項model.SelectedSystem是一個string type. 這作業得很好...
我面臨的問題是何時Model.System為空。
我的控制器看起來像這樣
public ActionResult Index()
{
var apiEntitySyncViewModel = new ApiEntitySyncViewModel
{
Systems = _entitySyncService.GetEnvironments(),
};
return View(apiEntitySyncViewModel);
}
運行時出現訊息 The ViewData item that has the key SelectedSystemOrigin is of type System.String but must be of type IEnumerable<SelectListItem>
我怎樣才能繪制一個空的 DropDownListFor 而不會出現那個錯誤
uj5u.com熱心網友回復:
試試這個
public ActionResult Index()
{
var apiEntitySyncViewModel = new ApiEntitySyncViewModel
{
Systems = _entitySyncService.GetEnvironments(),
};
if(apiEntitySyncViewModel.Systems==null) apiEntitySyncViewModel.Systems = new List <SelectListItem>();
//or you can try
new List <SelectListItem>{ new SelectListItem{ Value="0", Text ="Empty" }
return View(apiEntitySyncViewModel);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391531.html
標籤:C# html 阿贾克斯 asp.net-mvc 下拉列表
