开发者

View with complex view model

开发者 https://www.devze.com 2023-02-16 16:35 出处:网络
I am using ASP.NET MVC 3 and I have a view model as follows: public class RegistrationViewModel { public IList<LicenseViewModel> Licenses { get; set; }

I am using ASP.NET MVC 3 and I have a view model as follows:

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

public class LicenseViewModel
{
开发者_如何学Python    public string LicensedState { get; set; }
    public string LicenseType { get; set; }
}

A user can be licensed in multiple states and both the LicensedState and LicenseType values should be presented as dropdowns on the footer of a grid. How can I create a view with the RegistrationViewModel?


The Model

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

The View

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


You can have your view model like this:

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

LicensedStatesProvider and LicenseTypesProvider are simply way of getting all LicensedStates and LicenseTypes, it's up to you how to get them.

And in view, you'd have something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号