本文介绍了搜索ASP.NET MVC自定义路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的方案。对于这个例子可以说,我需要返回基于搜索标准的汽车名单。我想有一个单一的视图来显示结果,因为输出将是相同的,但我需要到达那里的几种方法。举例来说,我可能有一个文本框表单逐年进行搜索。我可能有一个包含所有红色,丰田车的超链接另一个单独的页面。我如何在同一个视图和控制器处理这些多个场景。我的困境是,搜索可能包含几个选项...年,制造商,型号等,但我不知道在哪里放了。

Here is my scenario. For the example lets say that I need to return a list of cars based on a search criteria. I would like to have a single View to display the results since the output will be the same, but I need several ways of getting there. For instance, I may have a Form with a textbox to search by year. I may have another separate page that contains a hyperlink for all red, Toyota cars. How do I handle these multiple scenarios in the same View and Controller. My dilemma is that the search could contain several options… year, make, model, etc but I don’t know where to put them.

,这是什么最好的方法?我是否应该路由定义参数或查询字符串去等?

What is the best approach for this? Should I define the parameters in the routing or go with query strings, etc?

推荐答案

选项1

当然,你总是可以选择/汽车/搜索方式/供应商=丰田和放大器;的color = red&放大器;模型= Corola,我认为这将是对你有好处

Of course you always can choose the way of /car/search/?vendor=Toyota&color=Red&model=Corola and I think it will be good for you.

routes.MapRoute(
    "CarSearch",
    "car/search",
    new { controller = "car", action = "search" }
);

您可以从Request.Params在这种情况下,行动取得PARAMS。

You can get params from Request.Params in action in this case.

选项2

,也可以定义在路由表中PARAMS,但据我所知它会被要求作出了一套所有可能的组合规则,因为PARAMS的命令事,例如:

Or you can define params in the routing table, but AFAIK it will be required to make a set of rules for all possible combinations, because an order of the params matter, for example:

        routes.MapRoute(
            "CarSearch1",
            "car/search/vendor/{vendor}/color/{color}/model/{model}",
            new {controller = "car", action = "search"}
        );

        routes.MapRoute(
            "CarSearch2",
            "car/search/color/{color}/vendor/{vendor}/model/{model}",
            new {controller = "car", action = "search"}
        );

        routes.MapRoute(
            "CarSearch3",
            "car/search/model/{model}/color/{color}/vendor/{vendor}",
            new {controller = "car", action = "search"}
        );

...的等等。如果你正在使用标准MvcRouteHandler会是真的。

... an so on. It's true if you are going with the standard MvcRouteHandler.

但它是一个简单的方法:)

But it was an easy ways :)

选项3

的辛苦,但是,我认为,最优雅的方式,就是让自己的IRouteHandler的实现 - 它会给你PARAMS为了更大的灵活性。但同样,它是一个艰辛的道路,不要用它去,如果你有一个简单的应用程序。
所以,只是为了示例的如何使它这种方式(非常简单的例子):

The hard, but, I think, most elegant way, is to make your own IRouteHandler implementation - it will give you much more flexibility in params order. But again, its a hard way, dont go with it if you have a simple app.So, just for example of how to make it this way (very simple example):

新路由添加到路由列表:

Add new route to the list of routes:

routes.Add
    (
        new Route
            (
                "car/search/{*data}",
                new RouteValueDictionary(new {controller = "car", action = "search", data = ""}),
                new MyRouteHandler()
            )
    );

添加将调整标准的请求处理链类:

Add classes that will tweak the standard request processing chain:

class MyRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpHandler(requestContext);
    }
}

class MyHttpHandler : MvcHandler
{
    public MyHttpHandler(RequestContext requestContext) : base(requestContext)
    {
    }

    protected override void ProcessRequest(HttpContextBase httpContext)
    {
        IController controller = new CarController();
        (controller as Controller).ActionInvoker = new MyActionInvoker();
        controller.Execute(RequestContext);
    }
}

class MyActionInvoker : ControllerActionInvoker
{
    protected override ActionResult InvokeActionMethod(MethodInfo methodInfo, IDictionary<string, object> parameters)
    {
        // if form of model/{model}/color/{color}/vendor/{vendor}
        var data = ControllerContext.RouteData.GetRequiredString("data");
        var tokens = data.Split('/');

        var searchParams = new Dictionary<string, string>();
        for (var i = 0; i < tokens.Length; i++)
        {
            searchParams.Add(tokens[i], tokens[++i]);
        }

        parameters["searchParams"] = searchParams;

        return base.InvokeActionMethod(methodInfo, parameters);
    }
}

在控制器:

public ActionResult Search(IDictionary<string, string> searchParams)
{
    ViewData.Add
        (
            // output 'model = Corola, color = red, vendor = Toyota'
            "SearchParams",
            string.Join(", ", searchParams.Select(pair => pair.Key + " = " + pair.Value).ToArray())
        );
    return View();
}

和它会与任何搜索参数工单:

And it will work with any search parameters order:

/car/search/vendor/Toyota/color/red/model/Corola
/car/search/color/red/model/Corola/vendor/Toyota
/car/search/model/Corola/color/red/vendor/Toyota

但也不要忘了做一个链接生成逻辑,因为Html.ActionLink和Html.RenderLink不会给你/汽车/搜索/模型/ Corola /颜色/红/供应商/丰田pretty形式url可,所以你需要做一个自定义链接生成。

But also dont forget to make a link generation logic, because Html.ActionLink and Html.RenderLink will not give you url in pretty form of /car/search/model/Corola/color/red/vendor/Toyota, so you'll need to make a custom link generator.

所以,如果你需要一个非常灵活的路由 - 你最好具有这种硬质的路要走:)

So, if you need a really flexible routing - you'd better go with this hard way :)

这篇关于搜索ASP.NET MVC自定义路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:40