Mona Coder
Mona Coder

Reputation: 6316

How to pass string as parameter in ASP.Net MVC

I am trying to make a simple sample of passing string parameter in URL not using the queryString at this example. First of all I added a new MapRouteto RouteConfig.cs file as

           routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
           routes.MapRoute(
                  name: "app",
                  url: "{controller}/{action}/{name}"
            );

and in Controller I have

 public class AppController : Controller
    {
        public string Index(string name)
        {
            return HttpUtility.HtmlEncode("Hello " + name );
        }
    }

but the view is not displaying the string parameter. For example a URL like this http://localhost:59013/App/Index/Ali only return Hello!

enter image description here

Why is this happening?

Update

  routes.MapRoute(
      name: "app",
      url: "{controller}/{action}/{name}",
      defaults: new {action = "Index" }
);
    routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

Upvotes: 1

Views: 2070

Answers (1)

haim770
haim770

Reputation: 49123

First, you need to change the order of your registered routes so the default will be the last.

Secondly, your app route pattern is wrong and will always collide with the default route. You better change its pattern to

url: "App/Index/{name}"

Or perhaps to the more friendlier

url: "App/{name}"

Both with

defaults: new { controller = "App", action = "Index" }

So that your routes would look like:

routes.MapRoute(
    name: "app",
    url: "App/{name}",
    defaults: new { controller = "App", action = "Index" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

See MSDN

Upvotes: 2

Related Questions