如何在不使用 FormsCollection 的情况下拥有两个不同的 ViewModel 并将数据从两个视图提交到控制器



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

我为它创建了一个PartialView和特定的ViewModel。为了能够只提交包含所有数据的 MainViewModel,我必须在视图和 PartView 的 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; }
}

将您的成员放在单独的班级中。

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

最新更新