首页 > 解决方案 > 如何在不使用 FormsCollection 的情况下拥有两个不同的 ViewModel 并将数据从两者提交到控制器?

问题描述

我有一个带有 2 DropDownListFor 的视图。这个 View 加载了某个 ViewModel。该流程要求当用户从视图中出现的第二个 DropDownListfor 中选择一个项目时,另一个 DropDownListFor 必须与其他数据一起显示。为了解决这个问题,我使用了一个使用 ajax 请求获得的 PartialView,并为这个 PartialView 使用了不同的 ViewModel。现在的问题是如何使用 ViewModel 而不是 FormsCollection 从 View 和 PartialView 提交数据?拥有两个不同的 ViewModel 是解决此类问题的正确方法吗?每个示例都显示每个 View 仅使用一个 ViewModel,但是如果在创建 View 时该 ViewModel 的数据没有全部加载会发生什么?

我为它创建了一个 PartialView 和特定的 ViewModel。为了能够只提交包含所有数据的 MainViewModel,我必须在 View 和 PartialView 的 ViewModel 上创建相同的属性。但这有意义吗?

public class AlertViewModel
{
        public string AlertDescription { get; set; }
        public List<DropdownModel> AlertTypesList { get; set; }
        public long SelectedAlertType { get; set; }
        public List<DropdownModel> CustomersList { get; set; }
        public long SelectedCustomer { get; set; }
        public long[] SelectedProducts { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
}

public class AlertProductListViewModel
{
        public long[] SelectedProducts { get; set; }
        public List<DropdownModel> ProductList { get; set; }
}

标签: c#asp.net-mvcrazor

解决方案


把你的成员放在分开的班级。

public class Alert
{
        public string AlertDescription { get; set; }
        public List<DropdownModel> AlertTypesList { get; set; }
        public long SelectedAlertType { get; set; }
        public List<DropdownModel> CustomersList { get; set; }
        public long SelectedCustomer { get; set; }
        public long[] SelectedProducts { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
}

public class AlertProduct
{
        public long[] SelectedProducts { get; set; }
        public List<DropdownModel> ProductList { get; set; }
}

  public class MyViewModel
  {
    public Alert Alert{ get; set; }
    public AlertProduct AlertProduct{ get; set; }        
  }
}

你的下拉菜单

@using SolutionPath.ProjectPath.ModelFolder.MyViewModel 
@Html.DropDownListFor(model => model.Alert.AlertTypesList)
@Html.DropDownListFor(model => model.Alert.CustomersList)
@Html.DropDownListFor(model => model.AlertProduct.ProductList)

你的控制器

public ActionResult MyController(MyViewModel viewModel)
{
  //Some code
  return view();
}

推荐阅读