0

on one of my page, I let user to filter the content based on the age they choose from the age dropdown list.

here's my code.

$('#age').change(function () {
         var ageUrl = "@Request.Url?age=" + $(this).val();

         alert(ageUrl);
         window.location = ageUrl;
     });

here's the problem. I am on the app page.

http:// localhost:60627/apps

first time, I choose an age and get redirected , no problem.

http:// localhost:60627/apps?age=Middle_School

second time, I pick another one.

http:// localhost:60627/apps?age=Middle_School?age=Preschool

in the querystring, age showed up twice. I tried both Request.Url or Request.RawUrl, always includes querystring. what should I use to get only page url without querystring.

qinking126
  • 11,385
  • 25
  • 74
  • 124

4 Answers4

7

I haven't really used this before but it does work:

 Request.Url.GetLeftPart(UriPartial.Path)

An alternative is:

 String.Format("{0}://{1}{2}",Request.Url.Scheme, Request.Url.Authority, Request.Url.LocalPath)

If you knew what controller/action you were on (from the ViewContext's data) you could use @Url.Action and specify the overload to force the http schema which would generate a full url as well.

Nick Bork
  • 4,831
  • 1
  • 24
  • 25
  • Like the idea of using the URL.Action as that is more of a convention. – Turnkey May 29 '12 at 17:01
  • your code works, but there's another easier way, i replaced Request.Url with Request.Url.AbsolutePath – qinking126 May 29 '12 at 17:28
  • I agree that AbsolutePath works but you made it seem like you wanted the schema/authority prefix on your Urls for some reason. Glad you got it working. – Nick Bork May 29 '12 at 19:26
1

Why don't you try Split method of string?

Request.Url.ToString().Split('?')[0]
VJAI
  • 32,167
  • 23
  • 102
  • 164
1

Why are you building the URL yourself? Let MVC do it for you:

@Url.Action("Action", "Controller", new { age = "Preschool" })

If age is not part of the route then it will be automatically added to the query string:

http://localhost:12345/Controller/Action?age=Preschool
Dismissile
  • 32,564
  • 38
  • 174
  • 263
  • The problem with this code is his function is JavaScript and your code is all server side. Unless he was to use a placeholder token like !age! and replace the token with a value from the text box your example would work. Ex: var ageUrl = @Url.Action("Action", "Controller", new { age = "!age!" })".replace('!age!',$(this).val()); – Nick Bork May 29 '12 at 19:29
0

This isn't a property of Request, but it may provide a solution for you. https://stackoverflow.com/a/2541083/969829

Community
  • 1
  • 1
DDevD
  • 1