2011-03-10 84 views
0

這裏是我的ViewModel,MVC生成DropDownLists動態

公共類FormGroupsAssociationViewModel:BaseViewModel {

public FormGroupsAssociationViewModel() 
    { 
     FormTypeFormGroupViewModels = new List<FormTypeFormGroupViewModel>(); 
    } 

    public FormGroupsAssociationViewModel(IList<FormTypeFormGroupViewModel> formTypeFormGroupViewModels) 
    { 
     this.FormTypeFormGroupViewModels = formTypeFormGroupViewModels; 

    } 

    public IList<FormTypeFormGroupViewModel> FormTypeFormGroupViewModels { get; set; } 

} 

公共類FormTypeFormGroupViewModel {

public FormTypeFormGroupViewModel() 
    { 

    } 

    public FormTypeFormGroupViewModel(FormType formType, IEnumerable<FormGroup> formGroups) 
    { 
     this.FormTypeId = formType.FormTypeID; 
     this.Title = formType.Title; 
     this.FormGroups = new SelectList(formGroups, "FormGroupId", "Title", "3"); 
    } 

    public int FormTypeId; 
    public string Title; 
    public SelectList FormGroups; 
    public int SelectedFormGroup; 

} 

和繼承人的看法:

@for (int i = 0; i < Model.FormTypeFormGroupViewModels.Count; i++) 
     { 
      <tr> 
       <td> 
        @Model.FormTypeFormGroupViewModels[i].Title 
       </td> 
       <td> 
        @Html.DropDownListFor(model => Model.FormTypeFormGroupViewModels[i].SelectedFormGroup, Model.FormTypeFormGroupViewModels[i].FormGroups) 
       </td> 
      </tr> 
     } 

終於控制器是:

[HttpPost] 
    [UnitOfWork] 
    public String Associations(FormGroupsAssociationViewModel model) 
    { 

     String s = string.Empty; 

     foreach (var formTypeFormGroupViewModel in model.FormTypeFormGroupViewModels) 
     { 
      s = s + formTypeFormGroupViewModel.SelectedFormGroup.ToString(); 
     } 

     return s; 

    } 

我有問題是SelectedFormGroup將返回0,而不是實際的了selectedValue。如果有人有任何想法,他們將不勝感激。

乾杯

加雷思

回答

0

解決了這個,

在我的視圖模型中,SelectedFormGroup被宣佈是這樣的:

public int SelectedFormGroup; 

這需要改爲:

public int SelectedFormGroup{get; set;}