Url.Action not giving me actual Url
asp.net-mvc, asp.net-mvc-3, javascript
Solution
You're using relative URLS. The relative url of your Index action of your default controller is "/". Try using
Url.Action("Index", "Search", null, Request.Url.Scheme)
if you need an absolute URL.
In your gloabal.asax you probably have a routing scheme that looks like:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Search", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The defaults are the controller/action that the routing uses if nothing is provided. If you removed the controller and action attributes from the last parameter then index and search would stop being your default action and controller. Now
@Url.Action("Index", "Search")
would yield "/Search/Index" because "/" is no longer a valid URL. I do NOT actually recommend doing this, but it's useful to know about in order to understand what's happening.
If before your default route you added
routes.MapRoute(
"Index", // Route name
"Search/Index/{id}", // URL with parameters
new { controller = "Search", action = "Index", id = UrlParameter.Optional } // Parameter defaults);
then all calls from `Url.Action("Search","Index")` would yield "/Search/Index" in the URL because they'd hit this routing first. However, entering no action or controller would still correctly bring you to your index page if entered directly into the browser.
Problem
I have a View called "Index". There's a search bar on the page and when you click submit, I have Javascript redirect: ``` var alerted='@url'; var url=alerted + "/" + $("#SearchText").val(); ``` In the Razor view, `url` is a variable defined as `var url = Url.Action("Index", "Search");` But in the Javascript, alerted outputs "/". I have no idea why this is. If I change it to another controller view, it's fine. But if I call the Index from Index, it gives me nothing. What gives? I need it to give me the url to the page that I'm at.