Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 URL parameters resolving to null

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?

like image 794
Richard Neil Ilagan Avatar asked Feb 23 '23 16:02

Richard Neil Ilagan


1 Answers

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
like image 66
gram Avatar answered Mar 03 '23 03:03

gram