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

时间:2012-04-20 10:12:18

标签: c# asp.net asp.net-mvc asp.net-mvc-3 razor

目前这就是我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而是将对象传递给不同的控制器及其视图?

1 个答案:

答案 0 :(得分:6)

为什么不直接将这两个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
}