将自定义参数传递给mvc3中的控制器

时间:2012-02-14 22:47:12

标签: c# .net asp.net-mvc asp.net-mvc-3

在定义路由表时,有没有办法将参数传递给控制器​​?

所以同一个控制器可用于两个或多个“部分”,例如

http://site.com/BizContacts   // internal catid = 1 defined in the route        
http://site.com/HomeContacts   // internal catid = 3
http://site.com/OtherContacts   // internal catid = 4

并且控制器获取路由表中定义的自定义参数,以通过该附加参数

过滤和显示数据

所以在上面的示例中,将显示索引操作,并且显示的数据将由诸如

之类的查询返回
 select * from contacts where cat_id = {argument} // 1 or 3 or 4

我希望这有点清楚

感谢任何帮助?

1 个答案:

答案 0 :(得分:1)

您可以编写自定义路线:

public class MyRoute : Route
{
    private readonly Dictionary<string, string> _slugs;

    public MyRoute(IDictionary<string, string> slugs)
        : base(
        "{slug}", 
        new RouteValueDictionary(new 
        { 
            controller = "categories", action = "index" 
        }), 
        new RouteValueDictionary(GetDefaults(slugs)), 
        new MvcRouteHandler()
    )
    {
        _slugs = new Dictionary<string, string>(
            slugs, 
            StringComparer.OrdinalIgnoreCase
        );
    }

    private static object GetDefaults(IDictionary<string, string> slugs)
    {
        return new { slug = string.Join("|", slugs.Keys) };
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }
        var slug = rd.Values["slug"] as string;
        if (!string.IsNullOrEmpty(slug))
        {
            string id;
            if (_slugs.TryGetValue(slug, out id))
            {
                rd.Values["id"] = id;
            }
        }
        return rd;
    }
}

可以在Application_Start中的global.asax注册:

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

    routes.Add(
        "MyRoute", 
        new MyRoute(
            new Dictionary<string, string> 
            { 
                { "BizContacts", "1" },
                { "HomeContacts", "3" },
                { "OtherContacts", "4" },
            }
        )
    );

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

最后你可以拥有你的CategoriesController:

public class CategoriesController : Controller
{
    public ActionResult Index(string id)
    {
        ...
    }
}

现在:

  • http://localhost:7060/bizcontacts将点击Index控制器的Categories操作并传递id = 1
  • http://localhost:7060/homecontacts将点击Index控制器的Categories操作并传递id = 3
  • http://localhost:7060/othercontacts将点击Index控制器的Categories操作并传递id = 4