3

I am sure this is a dupe, but I can't find the correct answer. It's simple enough. On a view in my application (that is within an Area if that matters) I need to get the url for a webapi controller in the root of my project (/api/settingscontroller).

How do I get this url in the view (via razor) so I can pass it into a javascript knockout view model?

Right now I have this:

ko.applyBindings(new UserSettingsViewModel('api/settings/', userId));

with appends that url to the location I am at. I want this:

locahost:1234/api/settings/

but I am getting this:

localhost:1234/settings/api/settings/

the first 'settings' in the url is the area that I am in.

ledgeJumper
  • 3,560
  • 14
  • 45
  • 92

1 Answers1

7
@Url.HttpRouteUrl("NameOfRoute", { controller = "Settings" })

or

@Url.RouteUrl("NameOfRoute", { httproute = "httproute", controller = "Settings" })

...as for the routeName parameter, I think usage of that might depend on whether or not you are using attribute routing or not. I believe the attribute routing that ships with MVC5 and WebAPI2 requires that your WebAPI attribute routes be named in order to be able to generate them with the UrlHelper (though it does not require that your MVC routes be named). If you are using traditional routing however, you may be able to omit the first parameter and not have to name the route at all.

One of the possible duplicates you were looking for may be here: How do I generate a webapi url from an MVC view?

Community
  • 1
  • 1
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • Thanks buddy, both for the answer, and elaborating so I can hopefully remember. :) – ledgeJumper Jan 11 '14 at 16:59
  • Also, not sure if you need this, but you may also want to add `Area = ""` to the second parameter in order to tell the `UrlHelper` to look in the root for the project, and not in the area where you are rendering it from. – danludwig Jan 11 '14 at 16:59
  • It figured it out for me, Im assuming from the NameOfRoute thing, which points to my root. Good call out though – ledgeJumper Jan 11 '14 at 17:10