在不知道确切数量的情况下将多个参数传递给 C# MVC 操作?

Pass multiple parameters to C# MVC action without knowing the exactly number?

是否可以在不知道确切数量的情况下将多个参数传递给 C# MVC 操作?

例如,我可以通过

mywebsite.com/brands/gm/ford/fiat/dodge

mywebsite.com/brands/gm/ford/fiat

但是,我不想创建如下路线:

"brands/{brand1}/{brand2}/{brand3}/{brand4}"

因为传递给它的品牌数量是可变的。

我怎样才能做到这一点?

从技术上讲,但只能通过使用通配符参数。然后,您负责自己从路径中解析出各个参数。例如:

routes.MapRoute(
    "Brands",
    "brands/{*brands}",
    new { controller = "Brands", action = "Index" }
);

根据您的第一个示例 URL,brands 参数的值将是字符串 "gm/ford/fiat/dodge"。然后您需要将其分解以获得各个品牌:

public ActionResult Index(string brands)
{
    var brandList = brands.Split("/");

    // do something with `brandList`
}

假设你有一个控制器方法:

public ActionResult Some(string brands)
{
    string[] individualBrands = brands.Split(';');

    return View();
}

url 看起来像:http://localhost:50006/Home/Some?brands=brand1;brand2