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

本文关键字:控制器 mvc3 自定义 参数传递 | 更新日期: 2023-09-27 18:24:50

在定义路由表时,是否有任何方法可以将参数传递给控制器?

因此同一个控制器可以用于两个或多个"部分",例如

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

我希望有点清楚

有什么需要帮忙的吗?

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

您可以编写一个自定义路由:

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

可以在CCD_ 2:中的CCD_

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

最后你可以拥有你的类别控制器:

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

现在:

  • http://localhost:7060/bizcontacts将命中Categories控制器的Index动作,并通过id=1
  • http://localhost:7060/homecontacts将命中Categories控制器的Index动作并通过id=3
  • http://localhost:7060/othercontacts将命中Application_Start1控制器的Index动作,并通过id=4