简体   繁体   English

将多个多值参数从不同的搜索表单传递给MVC控制器

[英]Passing multiple multivalued parameters to a MVC controller from different search form

I have a website with two search forms, both calling the same controller and action. 我有一个网站,有两个搜索表单,都调用相同的控制器和操作。 First form is for cars, second for motorcycles. 第一种形式用于汽车,第二种形式用于摩托车。 Each form has multiple search filters. 每个表单都有多个搜索过滤器。 These filters are multivalued. 这些过滤器是多值的。

My route file: 我的路线档案:

routes.MapRoute("Cars",
            "search/cars",
            new { controller = "Search", action = "Index", SearchType = "Cars", Param1 = "", Param2="" }, null);
routes.MapRoute("Motorcycles",
            "search/moto",
            new { controller = "Search", action = "Index", SearchType = "Moto", Param3 = "", Param4="" }, null);

So calling "mywebsite.com/search/cars?Param1=BMW&Param1=VW" should get me these values into my controller: 因此,调用“mywebsite.com/search/cars?Param1=BMW&Param1=VW”应该将这些值传递给我的控制器:

SearchType = "Cars"
Param1[] = {"BMW", "VW"}

Is there any way to avoid having action in Search controller declared as: 有没有办法避免在Search Controller中将操作声明为:

public ActionResult Index(string SearchType, string Param1, string Param2, string Param3, string Param4){}

But instead have one params[] variable which would then contain key value pairs? 但是有一个params []变量,然后包含键值对? Parameters in both cases have different names, so I can't always use the same name. 两种情况下的参数都有不同的名称,因此我不能总是使用相同的名称。 Also each search page has different number of parameters. 每个搜索页面也有不同数量的参数。

You may want to consider using JSON and doing a POST with a JSON object. 您可能需要考虑使用JSON并使用JSON对象执行POST。 If you're method is going to take a variety of parameters to the point where it could have 3-4+ params, then you should reconsider how the data is transferred. 如果你的方法是将各种参数带到可以有3-4 + params的点,那么你应该重新考虑如何传输数据。 Perhaps create a model for the search that has the filters as fields? 也许为搜索创建一个模型,将过滤器作为字段? You could then just accept the model as an object and handle it that way. 然后,您可以将模型作为对象接受并以此方式处理它。

You should also consider using two different actions on the Search controller. 您还应该考虑在搜索控制器上使用两个不同的操作。 Even though you're "searching", you've stated that each form handles different data, which means you will probably need to handle the search differently. 即使你正在“搜索”,你也说过每个表单处理不同的数据,这意味着你可能需要以不同的方式处理搜索。 Maybe use a Cars action and a Moto action? 也许使用汽车动作和Moto动作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM