MuriloKunze
MuriloKunze

Reputation: 15593

Parameter passing between actions

I tried this:

public ActionResult Index() // << it starts here
{
    return RedirectToAction("ind", new { name = "aaaaaaa" });
}

[ActionName("ind")]
public ActionResult Index(string name)// here, name is 'aaaaaaa'
{
    return View();
}

and it works..

so, I tried this:

[HttpPost]
public ActionResult Search(string cnpj) // starts here
{
    List<Client> Client = db.Client // it always find one client
        .Where(c => cnpj.Equals(c.Cnpj))
        .ToList();

    return RedirectToAction("Index", Client); // client is not null
}

public ActionResult Index(List<Client> Client) //but when goes here, client is always null
{
    if (Client != null)
        return View(Client);

    return View(db.Client.ToList());
}

Why it happens? Is there something wrong with the second code block?

Upvotes: 4

Views: 1010

Answers (2)

jkrieg
jkrieg

Reputation: 116

Ok, so your issue is that you are passing client as the parameter, but what your action method expects is an object containing a property "Client". Alternatively, it would work as you've written it if there is a route definition that specifically asks for a client parameter.

Upvotes: 0

gdoron
gdoron

Reputation: 150313

You can pass only primitive types in redirect, you can use the TempData for complicated types.

[HttpPost]
public ActionResult Search(string cnpj) // starts here
{
    List<Client> Client = db.Client // it always find one client
        .Where(c => cnpj.Equals(c.Cnpj))
        .ToList();

    TempData["client"] = Client;  //<=================
    return RedirectToAction("Index");
}

public ActionResult Index()
{
    var Client = TempData["client"];  //<=================

    if (Client != null)
        return View(Client);

    return View(db.Client.ToList());
} 

Basically TempData is just like saving data in the Session but the data will be deleted automatically in the end of the request where it was read.

TempData on MSDN

Notes:

  • The common naming convention in C# defined private variable to be camel-case. client instead of Client.
  • For List<Client> variable I would use clients as a name instead of client.
  • You should use a resource for the "client" string so it won't get out of sync, meaning one method puts the data in "Client" while the other looking for it in "client" or "Client Data"

Upvotes: 6

Related Questions