查看与复杂的视图模型

时间:2011-03-11 01:24:53

标签: c# asp.net asp.net-mvc-3 viewmodel

我正在使用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和LicenseType值都应显示为网格页脚上的下拉列表。如何使用RegistrationViewModel创建视图?

2 个答案:

答案 0 :(得分: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))
}

答案 1 :(得分: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)
}