【问题标题】:MVC 3 - Passing model to controller from different controllerMVC 3 - 将模型从不同的控制器传递给控制器
【发布时间】:2012-05-23 20:05:05
【问题描述】:

目前这是我在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);
}

这是我的SupplierIndex.cshtml

@model MyProject.Web.FormViewModels.SupplierFormViewModel

@foreach (var item in Model.Suppliers) {
  ...
  ...
}

除了使用TempData,还有其他方法可以将对象传递给不同的控制器及其视图吗?

【问题讨论】:

  • 为什么 SupplierController 不能为自己调用 service.Suppliers()
  • @Jeroen 我已经更新了问题并补充说service.Suppliers()HomeFormViewModel 获取属性。

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


【解决方案1】:

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

【讨论】:

  • 明白了!我知道这一点,我只是太累了,无法编写任何合适的代码。
  • 哈哈,我听到了,听起来像星期五综合症 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多