MVC 3 - 将模型从不同的控制器传递到控制器
本文关键字:控制器 模型 MVC | 更新日期: 2023-09-27 18:31:41
目前这是我HomeController
中的内容:
[HttpPost]
public ActionResult Index(HomeFormViewModel model)
{
...
...
TempData["Suppliers"] = service.Suppliers(model.CategoryId, model.LocationId);
return View("Suppliers");
}
这是我SupplierController
中的:
public ViewResult Index()
{
SupplierFormViewModel model = new SupplierFormViewModel();
model.Suppliers = TempData["Suppliers"] as IEnumerable<Supplier>;
return View(model);
}
这是我的Supplier
Index.cshtml
:
@model MyProject.Web.FormViewModels.SupplierFormViewModel
@foreach (var item in Model.Suppliers) {
...
...
}
除了使用TempData
之外,是否有另一种方法可以将对象传递给不同的控制器及其视图?
为什么不直接将这两个 ID 作为参数传入,然后从另一个控制器调用服务类?像这样:
有这样的SupplierController
方法:
public ViewResult Index(int categoryId, int locationId)
{
SupplierFormViewModel model = new SupplierFormViewModel();
model.Suppliers = service.Suppliers(categoryId, locationId);
return View(model);
}
然后,我假设您是通过某种链接从Supplier
视图中调用您的视图的?你可以做:
@foreach (var item in Model.Suppliers)
{
@Html.ActionLink(item.SupplierName, "Index", "Supplier", new { categoryId = item.CategoryId, locationId = item.LocationId})
//The above assumes item has a SupplierName of course, replace with the
//text you want to display in the link
}