2012-12-22 15 views
2

我想多個參數傳遞給一個動作在我的控制器:做這個傳遞多個參數,以行動

@Html.ActionLink("Set", "Item", "Index", new { model = Model, product = p }, null) 

我的操作方法是這樣的:

public ActionResult Item(Pro model, Pro pro) 
{ 
    ... 
} 

的問題是,在調用方法時,動作方法中的modelproductToBuy變量全部爲null。怎麼來的?

+5

因爲這個答案表明http://stackoverflow.com/a/4197843/168097您無法通過複雜的對象 –

+0

的後@Circadian引用做了解釋,你__could__序列化複雜的對象,並通過它的一個偉大的工作,你的控制器,但也是一個壞主意。恕我直言 - 在這方面有很多潛在的微妙混亂。考慮一下典型的編輯/編輯 - 保存方案,這個方案就像我們的模型對象從服務器轉到客戶端並且作爲一個對象返回到客戶端。但這僅僅是默認ModelBinding代表我們取消的一個技巧。 –

回答

3

不能發送複雜的對象的路線parameters.B'cos傳遞到行動時,它轉換成查詢字符串methods.So總是需要使用基本數據類型

應該看起來像下面(樣品)

@Html.ActionLink("Return to Incentives", "provider", new { action = "index", controller = "incentives" , providerKey = Model.Key }, new { @class = "actionButton" }) 

路由表應該看起來像基本數據類型的below.Consist。

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
      ); 

解決方案1 ​​

您可以從數據庫發送標識模型與ActionLink的參數,然後得到必要的對象進行進一步的處理控制器的操作方法中。

解決方案2

您可以使用TempData的從一個操作方法對象發送到另一個。它只是在控制器動作之間共享數據。您只應在當前和後續請求期間使用它。

舉個例子

型號

public class CreditCardInfo 
{ 
    public string CardNumber { get; set; } 
    public int ExpiryMonth { get; set; } 
} 

操作方法

[HttpPost] 
public ActionResult CreateOwnerCreditCardPayments(CreditCard cc,FormCollection frm) 
    { 
     var creditCardInfo = new CreditCardInfo(); 
     creditCardInfo.CardNumber = cc.Number; 
     creditCardInfo.ExpiryMonth = cc.ExpMonth; 

    //persist data for next request 
    TempData["CreditCardInfo"] = creditCardInfo; 
    return RedirectToAction("CreditCardPayment", new { providerKey = frm["providerKey"]}); 
    } 


[HttpGet] 
public ActionResult CreditCardPayment(string providerKey) 
    { 
    if (TempData["CreditCardInfo"] != null) 
     { 
     var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo; 
     } 

     return View(); 

    } 

如果您需要了解更多的TempData的細節,那麼你可以檢查我已經寫blog post

我希望這對你有幫助。