views:

139

answers:

2

Consider an ASP.NET MVC 1.0 project using the Areas convention as described on this Nov. 2008 Phil Haack blog post. This solution works great once it's set up!

My trouble is starting thanks to my limited knowledge of ASP.NET MVC's routing rules.

My intention is to create an action method and URL structure like this:

http://mysite/Animals/Dogs/ViewDog/Buster

DogsController.ViewDog() looks like this:

public ActionResult ViewDog(string dogName)
{
     if (dogName!= null)
     {
         var someDog = new DogFormViewModel(dogName); //snip a bunch more

         return View(someDog);
     }
     else { return View("DogNotFound"); }           
}

The task at hand is ensuring that the RegisterRoutes() has the correct entries.

UPDATE

Here's the new route being mapped:

routes.MapRoute("ViewDog", "Animals/{controller}/{action}/{dogName}",
                                     new { controller = "Dogs", 
                                           action = "ViewDog", dogName = "" });

The link to the URL is created:

<%= Html.RouteLink("Brown Buster", "ViewDog", new RouteValueDictionary(new { controller="Dogs", action="ViewDog", dogName="Buster" }))%>

The URL is created as expected. Thanks to Craig Stuntz and his blog post on Html.RouteLink.

http://mySite/Animals/Dogs/ViewDog/Buster

New Problem: The param dogName doesn't pickup the string value "Buster" from the URL. The call to the method succeeds, but the argument evaluates to null.

Questions

How can you:

  • make this route work with a string, and remove the default convention int id in the route? I'd like to change the name of the parameter away from int.
+1  A: 

Are you sure that ActionLink is actually matching the route you show them the question? When you have more than one route, I strongly recommend using RouteLink instead of ActionLink, as I explain in great detail in this post. When you use RouteLink, there is no possibility that you will match the wrong route, at least in URL generation.

Craig Stuntz
Thanks Craig. Appreciate the suggestion. I've used it, but a new problem exists now, where the argument passed to the method is null, even though I've explicitly sent it in the RouteLink. Any suggestions?
p.campbell
Now you're matching the wrong route on the way *in.* Get Phil Haack's routing debugger to see which route you're matching. It's not the one you want.
Craig Stuntz
A: 

The default parameter "id" doesn't have to be an int. It'll match whatever type you declare in your action method. Why not just do the following?

public ActionResult ViewDog(string id)
{
     if (id!= null)
     {
         var someDog = new DogFormViewModel(id); //snip a bunch more

         return View(someDog);
     }
     else { return View("DogNotFound"); }           
}
Chris