将多个参数传递给操作

时间:2012-12-22 17:45:01

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

我试图通过执行以下操作将多个参数传递给控制器​​中的操作:

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

我的行动方法如下:

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

问题是,在调用方法时,action方法中的modelproductToBuy变量都是null。怎么样?

1 个答案:

答案 0 :(得分:3)

无法发送复杂对象作为路由参数.B'cos在传递给操作方法时会转换为查询字符串。因此始终需要使用原始数据类型

它应该如下(样本)

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

您的路由表应如下所示。原始数据类型的原因。

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

解决方案1 ​​

您可以使用ActionLink将模型的Id作为参数发送,然后从数据库中获取必要的对象,以便在控制器的操作方法中进一步处理。

解决方案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

我希望这会对你有所帮助。