1

I have the following url

http://localhost/user/MyUserName

How do I get "MyUserName" from that url? So I can use it at the server side to retrieve the information I want to present to the client side?

In Django it was very simply to archive that. But how do I do that in ASP.net MVC4?

EDIT

routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );
2
  • MyUserName is always the last 'parameter' in the url? Commented Jun 21, 2012 at 11:30
  • @Exsaliver no that is the dynamic part of the url. It can be anything. But I want that parameter so I can fetch the userdata from the database. Commented Jun 21, 2012 at 11:52

1 Answer 1

3

I don't know what did you name your route parameter

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}", 
     new {controller = "Home", action = "Index", id = UrlParameter.Optional}, 
     null,
     new[] {"Project.Web.Controllers"});

But I suppose it's Id anyway try this:

var value = RouteData.Values["Id"];

Update :

In your case you should define a special route before " on top of " the default one :

routes.MapRoute(
    "ForUser",
    "User/{id}", 
     new {controller = "User", action = "UserInfo", id = UrlParameter.Optional}, 
     null,
     new[] {"Project.Web.Controllers"});
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, it is possible to get MyUserName if the url looks something like this http://localhost/User/UserInfo/MyUserName. Where User is the controller, and UserInfo is the action. But can I get my wanted parameter without the need of that extra part in the url?
I just want it to be http://localhost/User/MyUserName, but I don't want to change the route part.

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.