views:

195

answers:

1

Hi folks,

i wish to have the following url(s).. and i'm not sure how i should do the following:

1) Route registered in the global.asax
2) Controller method

Urls/Routes

- http://www.mysite.com/
- http://www.mysite.com/?page=2
- http://www.mysite.com/?tags=fooBar
- http://www.mysite.com/?page=2&tags=fooBar

Please note - i do not want to have http://www.mysite.com/{page}/{tags}/ etc.. if that difference makes sence. I also understand about the default routes, but i'm not sure how to tweak them to make it do what i require.

Lastly, i also know how to use Html.ActionLink(..) so I'm not worried about how to use that.

any suggestions?

Unit Testing

I'm also under the impression that i could do a unit test, like the following:- (using MvcFakes)...

// Arrange.
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);  

// Act.
context = new FakeHttpContext("~/?page=2&tags=fooBar");
routeData = routes.GetRouteData(context);

// Assert.
Assert.AreEqual("Home", routeData.Values["controller"]);
Assert.AreEqual("Index", routeData.Values["action"]);
Assert.AreEqual(2, routeData.Values["page"]);
Assert.AreEqual("fooBar", routeData.Values["tags"]);

Update 1

I'm hoping to run all these of the Index action on the default HomeController, if this helps. (in actual fact, I've renamed my HomeController to PostController but that is not really important / shouldn't effect the problem).

+1  A: 

Actually for what you are trying to do you don't need additional route. The default MVC route handles your request well. You just have to keep in mind that controller action parameter names must match your url param names.

URL: http://www.mysite.com/?page=2&tags=fooBar

public ActionResult Index(string page, string tags)
{
   ViewData["Message"] = string.Format("Page={0}, Tags={1}", page, tags);
   return View();
}

Of course thats for Controller "Home" and Action "Index" as defaults. But the point is clear I hope.

Scott Guthrie has excellent post about routing Here

Paul G.
So are you suggesting that I use the following route: routes.MapRoute("Home", "", new {controller = "Post", action = "Index"} <-- even though there are no defaults for page and tags? );
Pure.Krome
Oops. typo. controller = "Post" should read: new {controller = "Home"...}. soz.
Pure.Krome
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }); Yup default one, I've made sample project to try and it worked well.
Paul G.
Kewl! you're right!!! i thought that, if i had the method signature=> public ActionResult Index(string page, string tags) then i needed to have page and tags in the MapRoute(..) code, or otherwise it won't be able to find the correct Index method. kewl!!!!
Pure.Krome