0

I have an actionresult with two parameter:

 public ActionResult Index(int a,string b)
        {
            //some code

            return View(b);
        }

it creates this url automatically:

  mysite.com/a=1&b=http://site.com/b=1

I just need to show first parameter "a" in my url:

  mysite.com/a=1

I use the default route of MVC that creates in global.ascx:

 routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

what should i do? Thanks...

mortazavi
  • 401
  • 9
  • 22
  • What do you mean by it "creates this url automatically"? Also, are those supposed to be `mysite.com/?a=1`? – parKing Feb 19 '13 at 14:25
  • @parKing it means that this url is created automaticlly by using default route. i want to hidden b parameter from this url. can i do that? – mortazavi Feb 19 '13 at 15:27
  • Sorry, but I've never seen MVC "create" a URL. you should be able to hit that route with `mysite.com/?a=1`. Also, if you don't want `b`, why is it on the method? Does including it alter the functionality? If so, you could probably split them into two methods. – parKing Feb 19 '13 at 15:34

1 Answers1

0

If you are seeing the "b" parameter bleed through from the current request, you can set the "b" parameter explicitly to empty string to avoid this behavior:

@Html.ActionLink("Home", "Index", "Home", new { a = 1, b = "" }, null)

I reported this "feature" as a bug, but the developers at Microsoft seem to think this behavior is supposed to make your URLs easier to configure, and they don't intend to fix it.

What you're seeing here is a feature of routing where "ambient" values (i.e. values that were detected in the incoming request's URL) are used to simplify (sometimes...) the generation of routes to other pages.

You can check our my answer (under the name "Eilon") in this StackOverflow post, where I explain the behavior in a bit more detail: How Can I Stop ASP.Net MVC Html.ActionLink From Using Existing Route Values?

Ultimately if you want the most control over what gets generated for a URL there are a few options to consider:

  1. Use named routes to ensure that only the route you want will get used to generate the URL (this is often a good practice, though it won't help in this particular scenario)
  2. Specify all route parameters explicitly - even the values that you want to be empty. That is one way to solve this particular problem.
  3. Instead of using Routing to generate the URLs, you can use Razor's ~/ syntax or call Url.Content("~/someurl") to ensure that no extra (or unexpected) processing will happen to the URL you're trying to generate.

Thanks, Eilon

Community
  • 1
  • 1
NightOwl888
  • 55,572
  • 24
  • 139
  • 212