2

Hy Guys, I have to pass in a method action a string parameter, because I want to implement a tags' search in my site with asp.net MVC but everytime in action it is passed a null value.

I post some code!

I try to create a personal route.

 routes.MapRoute(
            "TagsRoute",
            "Tags/PostList/{tag}",
            new {tag = "" }
        );

My RouteLink in a viewpage for each tag is:

<% foreach (var itemtags in item.tblTagArt) {%> 

    <%= Html.RouteLink(itemtags.Tags.TagName,"TagsRoute", 
        new {tag=itemtags.Tags.TagName})%>,    
<% } %>

My method action is:

 public ActionResult PostList(string tag)
    {
        if (tag == "")
        {
            return RedirectToAction("Index", "Home");
        }
        else
        {
            var articoli = artdb.GetArticoliByTag(tag);

            if (articoli == null)
            {
              return RedirectToAction("Index", "Home");
            }

            return View(articoli);
        }
    }

Problem is value tag that's always null, and so var articoli is always empty!

Probably my problem is tag I have to make a route contrainst to my tag parameter.

Anybody can help me?

N.B I am using ASP.NET MVC 1.0 and not 2.0!

1
  • Hi, how about if (String.IsNullOrEmpty(tag)) instead of if (tag == "")? Commented May 8, 2010 at 11:03

1 Answer 1

4

Where did you put this custom route definition? It should be before the Default one.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "TagsRoute",
        "Tags/PostList/{tag}",
        new { controller = "Tags", action = "PostList", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Users", action = "Index", id = UrlParameter.Optional }
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! It does work :) So, the order of maproute is very important? And why, did in this way it does work? Thanks :)
Yes, the order is important. Routes are evaluated in the order they are declared and the first to match the request url is executed.
Ok, I understand, but this it explain because tag value is always null even if in reality I always pass it with RouteLink? And when it necessary specified an IrouteContraint? and If I pass a double? So RouteContraint it's useful only if we must specified the form of the parameter but not the type?
Did you mean 'tag = UrlParameter.Optional' in first MapRoute?

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.