簡體   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