问题描述
我使用匿名对象将我的 Html 属性传递给一些辅助方法.如果消费者没有添加 ID 属性,我想在我的辅助方法中添加它.
I use an anonymous object to pass my Html Attributes to some helper methods.If the consumer didn't add an ID attribute, I want to add it in my helper method.
如何向这个匿名对象添加属性?
How can I add an attribute to this anonymous object?
推荐答案
如果你想扩展这个方法:
If you're trying to extend this method:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
尽管我确信 Khaja 的对象扩展会起作用,但您可能会通过创建 RouteValueDictionary 并传入 routeValues 对象,从上下文添加其他参数,然后使用采用 RouteValueDictionary 而不是的 ActionLink 重载返回来获得更好的性能一个对象:
Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:
这应该可以解决问题:
public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
{
RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
// Add more parameters
foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
{
routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
}
return helper.ActionLink(linkText, actionName, routeValueDictionary);
}
这篇关于创建后将属性添加到匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!