3

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.

1
  • I've had this problem before too. It has something to do with the convention of the action named Index and coming from the same controller.. change the name of index to something else and try it Commented May 1, 2012 at 20:23

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know that would get past that relative url problem, thanks! I ended up renaming my Index actions to get around it.
Search/Index also happens to be my default URL in my global.asax, so on my local, the url appears as http://localhost:16721/. How can I get it to show as http://localhost:16721/Search/Index/ while still having it as my default in the global.asax?
The reason it resolves to "/" is the fact that the default Controller and Action match. That means "/" is the same as "/Search/Index". Its the same reason the default project isn't "/home/index".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.