2011-11-24 52 views
1

在我的項目中,DropDownListFor(x => x代碼位於EditorTemplate中,它用於填充數據表,其中一個表的字段是下拉列表,儘管一切都沒有問題呈現,但drop下拉列表不默認爲預先選定的項目我的視圖模型是設置什麼是我沒有看到DropDownListFor()沒有填充ViewModel中的預選項目?

代碼如下:?

視圖模型:

public class FooDetailViewModel : ViewModelBase 
{ 
    public List<FooPermissionObject> FooPermissions { get; set; } 
} 

強類型模型object:

public class FooPermissionObject 
{ 
    public string Name { get; set; } 
    public int Reason { get; set; } 
    public IEnumerable<SelectListItem> Reasons { get; set; } 
    public bool Selected { get; set; } 
} 

控制器:

var viewModel = new StockLineManagementDetailViewModel(); 

using (_model) 
{ 
    foreach (var company in _model.GetAllRecords<Company>()) 
    { 
     var permissionModel = new FooPermissionObject 
     { 
      Name = company.Name, 
      Selected = true, 
      Reasons = _model.GetAllRecords<FooPermissionReason>() 
        .ToList() 
        .Select(x => new SelectListItem 
        { 
         Value = x.FooPermissionReasonId.ToString(), 
         Text = x.FooPermissionReasonDesc 
        }), 
      Reason = record.FooPermissionReasonId 
     }; 

     viewModel.FooPermissions.Add(permissionModel); 
    } 
} 

的觀點:

<table id="myTable" class="tablesorter" style="width:98%"> 
    <thead> 
     <tr> 
     <th> 
      Name 
     </th> 
     <th> 
      Excluded 
     </th> 
     <th> 
      Reason for Exclusion 
     </th> 
     </tr> 
    </thead> 
    <tbody> 
     @Html.EditorFor(x => x.FooPermissions) 
    </tbody> 
</table> 

的EditorTemplate:

@model FooPermissionObject 
<tr> 
    <td> 
     @Html.DisplayFor(x => x.Name, new { @readonly = "readonly"}) 
     @Html.HiddenFor(x => x.Name) 
    </td> 
    <td> 
     @Html.CheckBoxFor(x => x.Selected) 
    </td> 
    <td> 
     @Html.DropDownListFor(x => x.Reason, Model.Reasons) 
    </td> 
</tr> 

任何人有任何想法,爲什麼這會不會與代表的對象填充DropDownListFor來自Reasons集合中的Reason價值?

回答

1

我不能看到你在你的選擇列表中設置選擇= true的代碼。您正在設置FooPermissionObject的Selected屬性,但這與您的下拉列表綁定到原因集合無關。你想要的東西是這樣的:

.Select(x => new SelectListItem 
{ 
    Value = x.FooPermissionReasonId.ToString(), 
    Text = x.FooPermissionReasonDesc, 
    Selected = (Some codition or other) 
}) 

替換一些條件或其他無論你的標準是說哪個項目應該選擇。

編輯:

一個更好的辦法可能是如下:

Reasons = new SelectList(_model.GetAllRecords<FooPermissionReason>(), 
         "FooPermissionReasonId", 
         "FooPermissionReasonDesc", 
         record.FooPermissionReasonId) 

到的SelectList的構造函數的PARAMS是:綁定集合,值字段,文本字段選擇的值。

+0

據我所知(這可能是錯誤的)設置Html幫手爲Html.DropDownListFor(x => x.Reason,Model.Reasons )自動綁定選定的項目作爲原因字段? – M05Pr1mty

+0

是的,用戶選擇的值將是在模型中爲原因屬性設置的值,但與預選項目無關。 –

+0

噢,真的嗎?所以即使遵循dasheddot的建議也不會起作用,因爲我仍然只設置用戶選擇內容時綁定的字段? – M05Pr1mty

0

編輯 另一種方式(現在是單向)將設置Selected屬性,同時投影到SelectListItem -List(如果需要)。

有關此主題的好文章可以在那裏找到:http://codeclimber.net.nz/archive/2009/08/10/how-to-create-a-dropdownlist-with-asp.net-mvc.aspx

+0

關於投影的SelectListItem的Iteresting點。我試試這個。 – M05Pr1mty

+0

只需告訴我是否需要進一步幫助 – dasheddot

+0

代碼的第一位不會編譯原因是int,您不能將其設置爲IEnumerable 。 –