2012-04-20 54 views
1

目前該控制器是我在我的HomeControllerMVC 3 - 傳遞模型從不同的控制器

[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有沒有不同的方式來傳遞對象到不同的控制器和它的視圖?

+0

爲什麼SupplierController不能自己調用​​'service.Suppliers()'? – Jeroen 2012-04-20 10:18:46

+0

@Jeroen我已經更新了這個問題,並補充說'service.Suppliers()'從'HomeFormViewModel'中獲取屬性。 – fuzz 2012-04-20 10:21:07

回答

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 
} 
+0

嘿!我知道這一點,我只是太累了,不能寫任何正確的代碼。 – fuzz 2012-04-20 10:42:15

+1

大聲笑我聽到雅,聽起來像星期五綜合症:) – mattytommo 2012-04-20 10:49:03

相關問題