MVC动态生成DropDownLists

时间:2011-03-10 13:15:32

标签: model-view-controller drop-down-menu

这是我的ViewModel,

public class 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。如果有人有任何想法,他们将不胜感激。

干杯

加雷

1 个答案:

答案 0 :(得分:0)

解决了这个问题,

在我的ViewModel中,SelectedFormGroup声明如下:

public int SelectedFormGroup;

这需要改为:

public int SelectedFormGroup{get; set;}