Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 列表排序-如何配置路由_C#_Asp.net Mvc_Asp.net Mvc Routing - Fatal编程技术网

C# 列表排序-如何配置路由

C# 列表排序-如何配置路由,c#,asp.net-mvc,asp.net-mvc-routing,C#,Asp.net Mvc,Asp.net Mvc Routing,我有一个视图,其中列出了一些数据。我想把它整理一下。问题是,我的路线已配置 routes.MapRoute( name: "Sort", url: "Cars/Index/SortBy/{column}", defaults: new { controller = "Cars", action = "Index", column = UrlParameter.Optional } ); 我总

我有一个视图,其中列出了一些数据。我想把它整理一下。问题是,我的路线已配置

    routes.MapRoute(
            name: "Sort",
            url: "Cars/Index/SortBy/{column}",
            defaults: new { controller = "Cars", action = "Index", column = UrlParameter.Optional }
            );
我总是在我的控制器类中得到null参数。我试着打开
/Cars/SortBy/columnname
/Cars/Index/SortBy/columnname
它不起作用。只有
/Cars/Index?sortBy=columnname
起作用

    public ActionResult Index(string SortBy)
    {
        switch (SortBy) // SortBy is null
        {
            case "manufactuer":
                return View(db.Cars.OrderBy(c => c.Model.Manufacturer.Name));
                break;

            case "model":
                return View(db.Cars.OrderBy(c => c.Model.Name));
        }

        return View(db.Cars);
    }

如何使其工作?

您应该将操作方法参数名称更改为
列,因为这是您在定义路由时使用的

public ActionResult Index(string column)
{
  return View();
}
然后它将用于url
Cars/Index/SortBy/model

如果希望它适用于url
Cars/SortBy/model
(不带索引),可以使用此路线定义

routes.MapRoute(
    name: "Sort",
    url: "Cars/SortBy/{column}",
    defaults: new { controller = "Cars", action = "Index", column = UrlParameter.Optional }
);
// Your other default route definition goes below this
或者,如果使用的是属性路由

[Route("Cars/SortBy/{column}")]
public ActionResult Index(string column)
{
   return View();
}
确保在
注册表项中启用属性路由
方法以使属性路由正常工作

public static void RegisterRoutes(RouteCollection routes)
{    
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();

    //Custom and default route definitions goes here
}