我想创建一个简单的 HtmlHelper.ActionLink
扩展,将值添加到路由值字典中。这些参数与 HtmlHelper.ActionLink
相同,即:
public static MvcHtmlString FooableActionLink(
this HtmlHelper html,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes)
{
// Add a value to routeValues (based on Session, current Request Url, etc.)
// object newRouteValues = AddStuffTo(routeValues);
// Call the default implementation.
return html.ActionLink(
linkText,
actionName,
controllerName,
newRouteValues,
htmlAttributes);
}
我添加到 routeValues
的逻辑有些冗长,因此我希望将其放入扩展方法助手中,而不是在每个 View 中重复它。
我有一个似乎有效的解决方案(作为下面的答案发布),但是:
- 对于如此简单的任务来说,似乎没有必要那么复杂。
- 所有的转换都让我觉得脆弱,就像在某些边缘情况下我会导致 NullReferenceException 或其他情况。
请发布任何改进建议或更好的解决方案。
最佳答案
public static MvcHtmlString FooableActionLink(
this HtmlHelper html,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes)
{
// Convert the routeValues to something we can modify.
var routeValuesLocal =
routeValues as IDictionary<string, object>
?? new RouteValueDictionary(routeValues);
// Convert the htmlAttributes to IDictionary<string, object>
// so we can get the correct ActionLink overload.
IDictionary<string, object> htmlAttributesLocal =
htmlAttributes as IDictionary<string, object>
?? new RouteValueDictionary(htmlAttributes);
// Add our values.
routeValuesLocal.Add("foo", "bar");
// Call the correct ActionLink overload so it converts the
// routeValues and htmlAttributes correctly and doesn't
// simply treat them as System.Object.
return html.ActionLink(
linkText,
actionName,
controllerName,
new RouteValueDictionary(routeValuesLocal),
htmlAttributesLocal);
}
关于asp.net-mvc - 附加到 HtmlHelper 扩展方法中的routeValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9130309/