Search code examples
c#asp.net-mvcasp.net-mvc-routing

Why isn't string parameter being routed to an action?


In my MVC5 application I am trying to pass a string to an action.

In PodcastsController I have an action called Tagged:

public ActionResult Tagged(string tag)
{
    return View();
}

For example, if I wanted pass the string Testto the Tagged action, it would look like this in the url:

/Podcasts/Tagged/Test

I have a route set up like this:

routes.MapRoute(
       "Podcasts",
       "Podcasts/Tagged/{tag}",
       new { controller = "Podcasts", action = "Tagged", tag = UrlParameter.Optional }
    );

Edit I am calling the Tagged action like this:

if (!string.IsNullOrEmpty(tagSlug))
{
    return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug });
}

When I set a break point on the Taggedaction, tag is always null

Can anyone see what I am doing wrong?

I'm pretty sure there's something wrong with the route but I can't figure out what...


Solution

  • The reason you are getting a null is because you are not actually passing it a parameter called tag in your code:

    if (!string.IsNullOrEmpty(tagSlug))
    {
        return RedirectToAction("Tagged", "Podcasts", new { tagSlug });
    }
    

    When you omit the property name it takes the variable name, so you are actually passing a variable tagSlug which your action does not accept. Try this instead:

    if (!string.IsNullOrEmpty(tagSlug))
    {
        return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug });
    }