【发布时间】:2016-08-03 07:06:05
【问题描述】:
我有一个有 2 个视图的模型: Create.chtml(使用@model Model1 添加新数据) Index.chtml(使用@model IEnumerable 循环遍历列表以查看当前数据)。
我希望在 1 个视图中同时具有添加和列表功能。由于视图中只能有 1 个模型语句,我该怎么做?此外,这不是 2 个不同的模型,而是同一个模型。
谢谢。
【问题讨论】:
标签: asp.net-mvc
我有一个有 2 个视图的模型: Create.chtml(使用@model Model1 添加新数据) Index.chtml(使用@model IEnumerable 循环遍历列表以查看当前数据)。
我希望在 1 个视图中同时具有添加和列表功能。由于视图中只能有 1 个模型语句,我该怎么做?此外,这不是 2 个不同的模型,而是同一个模型。
谢谢。
【问题讨论】:
标签: asp.net-mvc
您创建一个新的视图模型,其中包含列表和添加新项目的属性,
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<Customer> CustomerList { set;get;} public Customer NewCustomer {get;set;} } 只是一个想法。