Alex Fedotov
Alex Fedotov

Reputation: 55

ASP.NET MVC pass parameter as part of url

I'm trying to create well looking urls in my application, but when I'm using following construction

@Url.Action("Edit", "Account", new { userId = user.Id })

I've got next reference mysite.com/Account/Edit?userId=42.

How to get an url which looks like mysite.com/Account/Edit/42?

Upvotes: 3

Views: 10264

Answers (2)

Izzy
Izzy

Reputation: 6866

In your project under the App_Start folder you'll have a file named RouteConfig.cs this is where you can specify custom routing for your application.

By default you will have the following

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

Which will be hit if you did something like Url.Action("Edit", "Account", new {id = user.Id})

If you want to accomodate for your rule where you don't want to change userId to id then you can create one as follows:

  routes.MapRoute(
            name: "EditRule",
            url: "{controller}/{action}/{userId}",
            defaults: new { controller = "Edit", action = "Account", userId = UrlParameter.Optional }
        );

NOTE: the custom rule should appear before your default rule otherwise the default rule will be hit

Upvotes: 4

Rajan Mishra
Rajan Mishra

Reputation: 1178

Use

@Url.Action("Edit", "Account", new { Id = user.Id })

and also change userId to Id if you have used it in your **controller method** and **model logic**

`

Upvotes: 1

Related Questions