asp.net-mvc – 如何在Custom Helper中合并htmlAttributes
发布时间:2020-12-16 03:55:03 所属栏目:asp.Net 来源:网络整理
导读:我有一个自定义助手,我收到一个htmlAttributes作为参数: public static MvcHtmlString CampoTModel,TValue( this HtmlHelperTModel helper,ExpressionFuncTModel,TValue expression,dynamic htmlAttributes = null){ var attr = MergeAnonymous(new { @clas
我有一个自定义助手,我收到一个htmlAttributes作为参数:
public static MvcHtmlString Campo<TModel,TValue>( this HtmlHelper<TModel> helper,Expression<Func<TModel,TValue>> expression,dynamic htmlAttributes = null) { var attr = MergeAnonymous(new { @class = "form-control"},htmlAttributes); var editor = helper.EditorFor(expression,new { htmlAttributes = attr }); ... } MergeAnonymous方法必须返回参数中收到的合并后的htmlAttributes,其中包含“new {@class =”form-control“}”: static dynamic MergeAnonymous(dynamic obj1,dynamic obj2) { var dict1 = new RouteValueDictionary(obj1); if (obj2 != null) { var dict2 = new RouteValueDictionary(obj2); foreach (var pair in dict2) { dict1[pair.Key] = pair.Value; } } return dict1; } 在示例字段的编辑器模板中,我需要添加更多属性: @model decimal? @{ var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); htmlAttributes["class"] += " inputmask-decimal"; } @Html.TextBox("",string.Format("{0:c}",Model.ToString()),htmlAttributes) 我在编辑模板的最后一行的htmlAttributes中有的是: Click here to see the image 请注意,“类”正确显示,但扩展助手的其他属性在字典中,我做错了什么? 如果可能的话,我想只更改Extension Helper而不是Editor Template,所以我认为传递给EditorFor的RouteValueDictionary需要转换为匿名对象… 解决方法
我解决了现在更改所有编辑器模板的问题:
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); 为了这: var htmlAttributes = ViewData["htmlAttributes"] as IDictionary<string,object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); 和MergeAnonymous方法: static IDictionary<string,object> MergeAnonymous(object obj1,object obj2) { var dict1 = new RouteValueDictionary(obj1); var dict2 = new RouteValueDictionary(obj2); IDictionary<string,object> result = new Dictionary<string,object>(); foreach (var pair in dict1.Concat(dict2)) { result.Add(pair); } return result; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商
- asp.net-mvc – SportStore:WebUI.WindsorControllerFacto
- ASP.NET登录控件布局模板失败文本
- asp.net-web-api – 使用apicontroller对odata EntitySetCo
- asp.net – 错误HTTP 404.11通过查询字符串传递帐户激活令牌
- asp.net-mvc – Olark免费替代品
- asp-classic – If子句未按预期工作
- asp.net-mvc-3 – URL路由:如何将字符串作为我的ID?
- asp.net-mvc – ASP.NET MVC中的WebApi [FromUri]是什么?
- asp.net-core – 如何获取ASP.NET Core中的中间件列表
推荐文章
站长推荐
热点阅读