How can I make a route "{controller}/{action}/paramname/paramvalue/..." that applies to all my controllers?
As the title states, I'd like my MVC sites to have an URL pattern like
/Products/Category/Books/Sku/123456
Where every other url segment is /name/value of the parameter name and开发者_运维知识库 its value.
How can I do this?
ASP.NET routing allows to define catchall parameters at the end of route mask:
routes.MapRoute(
"CategoryWithParameters",
"Products/Category/{category}/{*parameters}",
new { controller = "Home", action = "Index" }
);
So this Home controller method
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();
}
and this view
<p>
@ObjectInfo.Print(ViewBag.category)
</p>
<p>
@ObjectInfo.Print(ViewBag.parameters)
</p>
<p>
@ObjectInfo.Print(ViewBag.values)
</p>
render URL h**p://localhost:32690/Products/Category/Books/Sku/123456/Bro/098765/df/34 to
精彩评论