无法在ASP.Net MVC中将字符串作为参数传递

时间:2016-09-21 17:02:46

标签: asp.net asp.net-mvc

我正在尝试在此示例中使用string在URL中传递queryString参数的简单示例。首先,我添加了一个新的MapRouteRouteConfig.cs文件

           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}"
            );

在Contoller中我有

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

但视图未显示字符串参数。例如这样的URL http://localhost:59013/App/Index/Ali仅返回Hello

enter image description here

你能告诉我为什么会这样吗?

  

更新

  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 }
            );

1 个答案:

答案 0 :(得分:2)

首先,您需要更改已注册路线的顺序,以便默认为最后一个。

其次,您的app路由模式错误,并且始终与默认路由冲突。您最好将其模式更改为

url: "App/Index/{name}"

或许更友好的

url: "App/{name}"

两者都有

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

这样你的路线就像:

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 }
);

请参阅MSDN