4

For some reason, whenever I try to resolve a URL with arguments in my local installation of ASP.NET MVC3, the arguments basically end up being null in my controller's handling function.

For example, I have

public class HomeController : Controller 
{
    public ActionResult Foo(string bar)
    {
        ViewBag.Message = bar;
        return View();
    }
}

and try to visit http://localhost/myapp/foo/sometext or http://localhost/myapp/home/foo/sometext, bar basically evaluates to null instead of sometext.

I'm fairly confident that my MVC3 install is working properly, as I've managed to run a separate app with a custom routing rule just a few days back. I'm kind of wary that I might have botched up a config flag somewhere or whatever.

Any ideas on what could be wrong here?

1 Answer 1

8

The default route mapping expects a parameter named id in your action.

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

If you change your action to this:

public ActionResult Foo(string id)

it should work. You could also try a URL like this if changing the parameter name isn't possible:

http://localhost/myapp/home/foo/?bar=sometext
Sign up to request clarification or add additional context in comments.

3 Comments

Huh. That definitely did the trick, thanks. However I was under the impression that I should be able to write a controller function like public ActionResult foo(string herp, string derp) {} and then automatically get to it via http://localhost/myapp/home/foo/1/2/ or something similar. Does this mean I'll have to author a custom route for every URL pattern I use in terms of number of arguments (and argument names)? That doesn't sound so convenient.
You would not be able to navigate to an action like public ActionResult foo(string herp, string derp) via http://localhost/myapp/home/foo/1/2/ without a custom route. But you would be able to submit a form via an HTTP POST to it without setting up a custom route as long as you have text boxes for herp and derp. In my experience, it hasn't been difficult to come up with a few conventions that satisfy all of my routing needs in a given project, but it depends on your requirements.
Yeah, I guess it's not too hard to actually come up with the routing rules in the long run. It's just a bit of a hard pill to swallow, especially since my MVC experience comes from CakePHP and CodeIgniter. But don't mind me. :D Thanks for the great help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.