开发者

asp.net mvc multiple parameters to an action, routing problem

My problem is that I give to my action 3 parameters (category, city, page) and some of them could be null because I need to make 3 filterings:

  • one by category (category != null && city == null)
  • one by city (category == null && city != null)
  • one by both of them (category != null && city != null)

My problem is on routing. When (category != null && city == null) it doesn't work. It gives to category parameter from my action null value, and my city parameter receives the category's value.

My Global.asax:

routes.MapRoute(
            "ListByCity",
            "Advertisers/{city}/{page}",
            new { controller = "Advertisers", action = "List"  }
            );

        routes.MapRoute(
            "ListByCategory",
            "Advertisers/{category}/{page}",
            new { controller = "Advertisers", action = "List" }
            );

        routes.MapRoute(
            "List",
            "Advertisers/{category}/{city}/{page}",
  开发者_运维知识库          new { controller = "Advertisers", action = "List" }
            );

Please help me.


think the problem in the opposite way. If you have the URL http://YourServer/Advertisers/Text How would you know if that text is a category or a city? You can resolve the matching problem with a regular expression but both cities and categories are strings so you have no way of telling the routing system which one to match. You will have to differenciate them. Maybe creating a route that matches /Advertisers/Categories/{category} and other that matches /Advertisers/Cities/{city}.


That looks more like three separate actions to me:

/Advertisers/List/{category}/{city}/{page}
/Advertisers/ListByCity/{city}/{page}
/Advertisers/ListByCategory/{category}/{page}

These can all call a common method in your controller to prepare a model for your List view.

EDIT:

Or you need to add a category called "all" and a city called "all" and then you can get away just one route:

/Advertisers/List/{category}/{city}/{page}


Its best to use querystrings.

Please refer to https://stackoverflow.com/questions/4.....

It has quite a few good suggestions too.


I agree with @MCL's edit.. I think you can take that approach without having an action as well.

/Advertisers/All/NewYork/1
/Advertisers/SomeCategory/NewYork/2

You setup your route something like this:

routes.MapRoute(
        "List",
        "Advertisers/{category}/{city}/{page}",
        new { controller = "Advertisers", action = "List" });

And your Action would look something think this:

public ActionResult List ( string category, string city, int page ) { .. }

I also disagree with query strings in this case. Its easier, sure, but I feel like this URI pattern would be a core part of your app and not setting up a proper route system for it would hinder you in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜