Mona Coder Mona Coder - 2 months ago 5
ASP.NET (C#) Question

Not Able 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
MapRoute
to
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 Contoller 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

Can you please let me know why this is 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 }
);

Answer

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

Comments