MVC 3 - 将模型传递给不同控制器的控制器

fuz*_*uzz 1 c# asp.net asp.net-mvc razor asp.net-mvc-3

目前这就是我的意思HomeController:

[HttpPost]
public ActionResult Index(HomeFormViewModel model)
{
    ...
    ...

    TempData["Suppliers"] = service.Suppliers(model.CategoryId, model.LocationId);

    return View("Suppliers");
}
Run Code Online (Sandbox Code Playgroud)

这就是我的意思SupplierController:

public ViewResult Index()
{
    SupplierFormViewModel model = new SupplierFormViewModel();
    model.Suppliers = TempData["Suppliers"] as IEnumerable<Supplier>;

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

这是我的Supplier Index.cshtml:

@model MyProject.Web.FormViewModels.SupplierFormViewModel

@foreach (var item in Model.Suppliers) {
  ...
  ...
}
Run Code Online (Sandbox Code Playgroud)

而不是使用TempData是否有不同的方式将对象传递给不同的控制器及其视图?

mat*_*mmo 6

为什么不直接将这两个ID作为参数传递,然后从另一个控制器调用服务类?就像是:

你的SupplierController方法是这样的:

public ViewResult Index(int categoryId, int locationId)
{
    SupplierFormViewModel model = new SupplierFormViewModel();
    model.Suppliers = service.Suppliers(categoryId, locationId);

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

然后,我假设您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
}
Run Code Online (Sandbox Code Playgroud)