繁体   English   中英

带有复杂视图模型的视图

[英]View with complex view model

我正在使用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创建视图?

该模型

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))
}

您可以使用如下视图模型:

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM