Asp.Net MVC Route Table and Controller Actions
-
19-08-2019 - |
Question
I am creating a directory of sorts with members and their profiles. I'm using the MVC framework in .net.
I have a view that allows you to find members based on some criteria so my controller has a Find() action result, then another that accepts the post verb. So, somesite.com/members/find displays the search tools, then once the form has been submitted the same url displays the results. I now want the member name to link to another actionresult method in the same controller for displaying their profile and i want the url's to follow this pattern somesite.com/members/{username}.
How do i create a controller method that will do this?
Is there more to it than that?
Do i need to map new routes in the global.asax?
Thanks for the help.
Solution
First create your action method on the controller like this:
public ActionResult Profile(string userName)
{
// Do What you want with the userName
throw new System.NotImplementedException();
}
Then create a new route in your global.asax file to handle the somesite.com/members/{username} like this:
routes.MapRoute(
"Profile",
"members/{username}",
new { controller = "Members", action = "Profile", userName = "" }
);
That's it. I am not sure what you are calling the controller that will host the action method. I assumed members.