0

I'm practicing ASP.NET MVC routing and now I'm stuck at a situation which I don't understand how to solve. I have two controllers and action in both controllers and two routes in RouteConfig class - which looks like this:

routes.MapRoute(
        name: "Students",
        url: "{Class}/{Students}",
        defaults: new { controller = "Class", action = "Students" });
        
        routes.MapRoute(
        name: "SubjectDetail",
        url: "{Class}/{Subject}",
        defaults: new { controller = "Subject", action = "SubjectDetail"});

Now the problem is when I go to the class/Students URL, it works fine, but in case of class/subject, it again redirects me to the class/Students URL.

I know there is some route pattern mistakes. How to solve this issue?

Thanks

5
  • 1
    but in case of class/subject it again redirects me to the class/Students -- That's because both of your routes have the same signature. How is the routing engine supposed to differentiate between a student and a subject, if both URLs look the same? Commented May 29, 2018 at 17:29
  • That's why i ask. How can i differentiate?. How can I use same pattern for different controllers? Commented May 29, 2018 at 17:31
  • Your urls are exactly the same even though the template variables ({Students}, {Subject}) have different names. For example if you call cs101/bob, there is no way to know whether bob is a student or a subject. Since the Students route is defined first, it uses it. Commented May 29, 2018 at 17:31
  • 1
    You should add something to the route to differentiate it use {Class}/Students/{Name} and {Class}/Subject/{Title} , for example. Commented May 29, 2018 at 17:33
  • Yeah I think this could work. Thanks. Commented May 29, 2018 at 17:43

1 Answer 1

1

Try:

routes.MapRoute(
        name: "Students",
        url: "classes/{classId}/students/{studentId}",
        defaults: new { controller = "Class", action = "Students" });

        routes.MapRoute(
        name: "SubjectDetail",
        url: "classes/{classId}/subjects/{subjectId}",
        defaults: new { controller = "Subject", action = "SubjectDetail"});
Sign up to request clarification or add additional context in comments.

Comments

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.