简体   繁体   中英

Passing multiple parameters to action

I am trying to pass multiple parameters to an action in my controller by doing this:

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

My action method looks like this:

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

The problem is that the model and productToBuy variables in the action method are all null when the method is called. How come?

You cannot send complex objects as route parameters.B'cos it's converted into query string when passing to the action methods.So always need to use primitive data types .

It should be looks like below (sample)

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

Your route table should be looks like below.Consist of primitive data types.

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

Solution 1

You can send a Id of the model as a parameter with ActionLink and then get the necessary object from the database for further processing inside the controller's action method.

Solution 2

You can use TempData for send objects from one Action Method to another. Simply it's share data between controller actions.You should only use it during the current and the subsequent requests only.

As an example

Model

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

Action Methods

[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();
          
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM