tags:

views:

69

answers:

1

I see that there is Controller.RedirectToAction(string actionName, string controllerName, object values) but I never got the values parameter to work. Consider I want to do the following overload of actions in a controller:

public ActionResult Read() 
{
    return RedirectToAction("ReadPage", "MyController", 1);
}

public ActionResult ReadPage(int page)
{
    // Doing the actual stuff 
}

…I get exception when I try to go to the Read action. The same goes with Html.ActionLink.

What's up with that? Can you pass values to controllers without going to the browser at all in MVC?

+2  A: 

Try using:

return RedirectToAction("ReadPage", "MyController", new {page = 1});

It needs to know which argument you mean (as in the more general case, you can have lots of parameters), which it can infer from the above.

The anonymous type pattern (above) is very cmomon in ASP.NET MVC, although in many cases I believe you can also give it a populated dictionary to mean the same.

Also - there is no need for two actions in this case; you can set up your routes to supply default values; here's some I posted earlier:

    public ActionResult Search(string query, int startIndex, int pageSize)
    {
        ...
    }

with routes:

    routes.MapRoute("Search", "Search/{query}/{startIndex}",
             new {
                controller = "Home", action = "Search",
                startIndex = 0, pageSize = 20
             });

Now if I don't supply a startIndex, it passes 0 to my Search by default. So I can navigate to "/Foo" for a default search, or "/Foo/100" to do the same search starting at 100. Alternatively, the args can be on the query string, and will still get defaulted using the values from the anon-type.

Marc Gravell
Ah. That works. Thanks!
Spoike