【问题标题】:Pass Model and IEnumerable<Model> of same model in 1 view [duplicate]在 1 个视图中传递同一模型的模型和 IEnumerable<Model> [重复]
【发布时间】:2016-08-03 07:06:05
【问题描述】:

我有一个有 2 个视图的模型: Create.chtml(使用@model Model1 添加新数据) Index.chtml(使用@model IEnumerable 循环遍历列表以查看当前数据)。

我希望在 1 个视图中同时具有添加和列表功能。由于视图中只能有 1 个模型语句,我该怎么做?此外,这不是 2 个不同的模型,而是同一个模型。

谢谢。

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

您创建一个新的视图模型,其中包含列表和添加新项目的属性,

public class CustomerListViewModel
{
   public List<Customer> CustomerList { set;get;}  // For showing the existing list

   // The below properties are for adding new customer
   public string NewCustomerName { set;get;}
   public string NewCustomerEmail { set;get;}
}
public class Customer
{
   public string Name { set;get;}
}

现在在您的 GET 操作中,创建一个对象,加载 CustomerList 属性并将其发送到视图

public ActionResult Index()
{
  var vm = new CustomerListViewModel();
  //Hard coding 2 customers for demo. you may replace with data from db
  vm.CustomerList= new List<Customer> {
                                        new Customer  { CustomerName ="Scott"},
                                        new Customer  { CustomerName ="John"},
  };
  return View(vm);
}

现在您的视图将被强类型化到这个新的视图模型

@model CustomerListViewModel
<h2>Existing customers</h2>
@foreach(var c in Model.CustomerList)
{
  <p>@c.Name</p>
}
<h3>Add new customer</h3>
@using(Html.BeginForm("Add","Customer"))
{
  @Html.LabelFor(s=>s.NewCustomerName)
  @Html.TextBoxFor(s=>s.NewCustomerName)

  @Html.LabelFor(s=>s.NewCustomerEmail)
  @Html.TextBoxFor(s=>s.NewCustomerEmail)
  <input type="submit" />
}

并且在您的 Add HttpPost 操作中,您可以使用与参数相同的视图模型

[HttpPost]
public ActionResult Add(CustomerListViewModel model)
{
  var name = model.NewCustomerName;
  var email = model.NewCustomerEmail;
  // Save this
  // to do  :Return something (Redirect to success page)
}

【讨论】:

  • 建议:与其填充属性,不如只包含对象的一个​​属性。喜欢public class CustomerListViewModel { public List&lt;Customer&gt; CustomerList { set;get;} public Customer NewCustomer {get;set;} } 只是一个想法。
  • 然后您需要操作表单控件名称,以便模型绑定工作。这就是我个人更喜欢精益平面视图模型的原因。好吧,就是它们被称为“视图模型”,它们是特定于视图的。
  • 我理解你的想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2021-08-20
  • 2015-10-30
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多