ASP.NET MVC: Proper way to consume/link to a resource from another controller
-
18-09-2019 - |
Question
In a view, I want to consume some Json produced by an action on another controller. I don't think I ought to be arbitrarily specifing the url for the resource because if I say something like "/Dealerships/GetDealerData" and if my application is a virtual directory at say "www.somesite.com/MyApplication", then my reference to that resource would break.
I'm sure there's something to do w/ Routes that will allow me to correctly generate the url of the resource by specifing the controller and action name but I don't know what it is and am having difficulty finding it. Can someone please point me in the right direction?
Solution
You can use Url.Action(). Something like this:
<%=Url.Action("MyAction", "MyController")%>
This is the same as <%=Html.ActionLink("MyAction", "MyController")%>
but only generating the url, not the <a />
tag.