MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Redirect to action passes null instead of object

My MVC4 project uses the RedirectToAction() to pass values to another controller.

The problem is, it passes null instead of a value

    [HttpGet]
    public ActionResult MyProduct(product prod)
    {
        return RedirectToAction("Index", "MyController", new { prod = prod});
    }

This accurately redirects to my MyController which is

    public ActionResult Index(Product prod)
    {
        // prod is null :(
    }

I put on a watch in the MyProduct controller, the prod object has a value. The properties do not have values :( it is null

Why does it become null when I pass the object between controllers?

Upvotes: 2

Views: 6073

Answers (2)

Tushar Gupta
Tushar Gupta

Reputation: 15943

You mistyped you parameter name that you are expecting at your action change it to prod because the prod is a part of RouteValueDictionary which will be collected by the same parameter as defined askey in the dictionary

return RedirectToAction("Index", "MyController", new { prod = prod});

Update

You cannot pass a model object via route parameters via RedirectToAction if I understood your question correctly, instead you can pass specific properties required to be send or you can use the TempData

You can't send data with a RedirectAction. That's because you're doing a 301 redirection and that goes back to the client.

When you redirect you mainly have the query string as a means to pass data to the other request. The other approach is to use TempData which stores data away on the server and you can retrieve it on the next request. By default TempData uses Session.

Consider this image for getting the ways of passing data between Model-View-Controller enter image description here

Upvotes: 4

Joce Pedno
Joce Pedno

Reputation: 334

Your function parameter name doesn't match in your RedirectToAction().

You should change it like this:

return RedirectToAction("Index", "MyController", new { prod = prod});

Upvotes: 0

Related Questions