2011-03-11 69 views
0

我使用ASP.NET MVC 3,我有一个视图模型如下:视图复杂视图模型

public class RegistrationViewModel 
{ 
    public IList<LicenseViewModel> Licenses { get; set; } 
} 

public class LicenseViewModel 
{ 
    public string LicensedState { get; set; } 
    public string LicenseType { get; set; } 
} 

用户可以在多个国家获得许可,并同时LicensedState和授权类型的值应呈作为网格页脚的下拉菜单。我如何使用RegistrationViewModel创建视图?

回答

1

你可以有你的视图模型是这样的:

public class LicenseViewModel 
{ 
    public IEnumerable<SelectListItem> LicensedState { get; private set; } 
    public IEnumerable<SelectListItem> LicenseType { get; private set; } 

    public LicenseViewModel(string licensedState = null, string licenseType = null) 
    { 
    LicensedState = LicensedStatesProvider.All().Select(s=> new SelectListItem 
     {Selected = licensedState!= null && s == licensedState, Text = s, Value = s}); 
    LicenseType = LicenseTypesProvider.All().Select(t => new SelectListItem 
     { Selected = licenseType != null && t == licenseType, Text = t, Value = t }); 
    } 
} 

LicensedStatesProviderLicenseTypesProvider只是让所有LicensedStates和LicenseTypes的方式,就看你如何得到它们。

,并考虑,你有这样的事情:

@foreach (var license in Model.Licenses) 
{ 
    //other stuff... 
    @Html.DropDownList("LicensedState", license.LicensedState) 
    @Html.DropDownList("LicenseType", license.LicenseType) 
} 
4

示范

public class RegistrationViewModel 
{ 
    public IList<LicenseViewModel> Licenses { get; set; } 
} 

public class LicenseViewModel 
{ 
    public string LicensedState { get; set; } 
    public string LicenseType { get; set; } 

    public IEnumerable<LicenseState> LicenseStates { get; set; } 
    public IEnumerable<LicenseType> LicenseTypes { get; set; } 
} 

@model RegistrationViewModel 

@foreach (var item in Model) 
{ 
    @Html.DropDownListFor(model => model.LicensedState, new SelectList(item.LicenseStates, item.LicenseState)) 
    @Html.DropDownListFor(model => model.LicenseType, new SelectList(item.LicenseTypes, item.LicenseType)) 
}