2011-08-18 26 views
0

在下面的代碼中,儘管model.Title保存了正確的選定值,但它沒有在ddl中設置,ID爲'Title'。在MVC3.0的HTML.Dropdownlistfor中填充選定值的替代方法

我可以用其他方式設置選定的值嗎? (如在文件準備好了?)

<td> 
@Html.DropDownListFor(model => model.Title, Model.TitleList, !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" }) 
</td> 

在我的控制器選擇列表的是越來越充滿如下:

model.TitleList = new SelectList(GetAllTitles(), "Code","Value"); 

在這種情況下,我爲使用其他的重載方法,如何設置selectedValue屬性這個selectList的?

+0

可以顯示設置model.TitleList和設置model.Title的代碼的代碼嗎? –

回答

1

如果Model.TitleListSelectList,則可以在創建模型期間填充SelectList時指定所選值。舉例說明:

var model = new MyViewModel(); 
var domainEntity = GetMyDomainEntity(id); 

// Create a selectlist using all your titles and specifying the Title value of the item 
// you're viewing as the selected item. See parameter options if you're not supplying 
// an object as the selected item value 
model.TitleList = new SelectList(GetAllTitles(), domainEntity.Title) 

然後,您只需在您的視圖中執行Html.DropDownListFor即可。

+0

但是在我的控制器中,selectlist被填充如下:model.TitleList = new SelectList(GetAllTitles(),「Code」,「Value」);在這種情況下,因爲我使用其他重載的方法,如何設置此selectList的selectedValue屬性? – Biki

+0

您可以將其填充爲「模型」。TitleList = new SelectList(GetAllTitles(),「Code」,「Value」,domainEntity.Title)'。基本上添加第四個參數,即選定的項目。 –

3

如果創建model.TitleList作爲一個IEnumerable <SelectListItem>,在這裏你都設置文本的SelectListItems 的model.Value是SelectListItems的值之一的值然後一切都應該工作。所以:

model.TitleList = GetAllTitles() 
      .ToList() 
      .Select(i => new SelectListItem { 
           Value = i.Id.ToString(), 
           Text = i.Description }); 

model.Title = 5; 

,並在您查看:

<td> 
@Html.DropDownListFor(model => model.Title, 
         Model.TitleList, 
         !Model.IsTitleEditable 
         ? (object)new { @disabled = "disabled", @style = "width:250px;" } 
         : (object)new { @style = "width:250px" }) 
</td> 

注意,ID = 「標題」 是不是在HtmlAttributes必要,助手將創建一個Id爲您服務。

編輯 有關於在SelectListItemSelected屬性有些混亂。這是不是使用時使用DropDownListFor,它只在DropDownList中使用。因此,對於DropDownListFor,您可以將模型的屬性設置爲您要選擇的值(上述model.Title = 5;)。

1

Personnaly是我喜歡做的是有一個靜態類,像這樣:

public static class SelectLists 
{ 
    public static IList<SelectListItem> Titles(int selected = -1) 
    { 
     return GetAllTitles() 
      .Select(x => new SelectListItem { 
        Value = x.Id.ToString(), 
        Text = x.Description, 
        Selected = x.Id == selected 
       }).ToList(); 
    } 
} 

然後在我的觀點:

@Html.DropDownListFor(x => x.Title, SelectLists.Titles(Model.Title), !Model.IsTitleEditable ? (object)new { id = "Title", @disabled = "disabled", @style = "width:250px;" } : (object)new { id = "Title", @style = "width:250px" }); 

我所有的SelectLists是在類中,如果我有他們中的太多我會在不同的課程中分開。

我覺得它很有用,因爲如果您需要在另一個視圖/動作中使用相同的dropdownlist,則不必在控制器中重複該代碼。

相關問題