gpt4 book ai didi

asp.net-mvc-3 - 如何创建适用于我所有 Controller 的路由 "{controller}/{action}/paramname/paramvalue/..."?

转载 作者:行者123 更新时间:2023-12-03 04:50:18 26 4
gpt4 key购买 nike

正如标题所述,我希望我的 MVC 站点具有如下 URL 模式

/Products/Category/Books/Sku/123456

其中每个其他 url 段都是参数名称及其值的/name/value。

我该怎么做?

最佳答案

ASP.NET 路由允许在路由掩码末尾定义catchall参数:

routes.MapRoute(
"CategoryWithParameters",
"Products/Category/{category}/{*parameters}",
new { controller = "Home", action = "Index" }
);

所以这个家庭 Controller 方法

public ActionResult Index(string category, string parameters)
{
// slashes were ignored by routing system
string[] parts = parameters.Split('/');

Dictionary<string, string> values = new Dictionary<string, string>();

// we want only keys with values
for (int i = 0; i < parts.Length / 2 * 2; i += 2)
values[parts[i]] = parts[i + 1];

ViewBag.category = category;
ViewBag.parameters = parameters;
ViewBag.values = values;

return View();
}

和这个 View

<p>
@ObjectInfo.Print(ViewBag.category)
</p>
<p>
@ObjectInfo.Print(ViewBag.parameters)
</p>
<p>
@ObjectInfo.Print(ViewBag.values)
</p>

渲染 URL h**p://localhost:32690/Products/Category/Books/Sku/123456/Bro/098765/df/34 至

rendered view

关于asp.net-mvc-3 - 如何创建适用于我所有 Controller 的路由 "{controller}/{action}/paramname/paramvalue/..."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5157266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com