2011-08-18 58 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,则不必在控制器中重复该代码。

相关问题