MvcHtmlString解决MVC中从后台返回HTML代码被编码问题
- (1) 要得到的效果
<a class="easyui-linkbutton" data-options="iconCls:'icon-add'" id="dgRowAdd" plain="true">新增行</a>
- (2) 属性内编码被转换
<a class="easyui-linkbutton" data-options="iconCls:'icon-add'" id="dgRowAdd" plain="true">新增行</a>
- (3) 全部被转换
<a class="easyui-linkbutton" data-options="iconCls:&#39;icon-add&#39;" id="dgRowAdd" plain="true">新增行</a>
(2) (3)都不是我要的结果
因此我找了些资料,统和了下,最终转换的时候在最后代码输出的时候将HTML转换一下 HttpUtility.HtmlDecode
/// <summary> /// DataGrid /// Toolbar /// </summary> /// <param name="helper"></param> /// <param name="id"></param> /// <param name="text"></param> /// <param name=""></param> /// <param name="token"></param> /// <param name="role"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString ToolbarFor(this HtmlHelper helper, string id, string text, string css, dynamic htmlAttributes) { var builder = new TagBuilder("a"); builder.IdAttributeDotReplacement = "-"; builder.GenerateId(id); var dic = new RouteValueDictionary(htmlAttributes); Dictionary<string, object> dicAttrs = new Dictionary<string, object>(); string token = string.Empty; string role = string.Empty; foreach (var item in dic) { switch (item.Key) { case "options": dicAttrs.Add("data-options", item.Value); break; case "token": token = Convert.ToString(item.Value); break; case "role": role = Convert.ToString(item.Value); break; default: dicAttrs.Add(item.Key, item.Value); break; } } if (!string.IsNullOrEmpty(token)) { if (string.IsNullOrEmpty(role)) { return MvcHtmlString.Create(""); } if (MasterPermissionAuthorizeAttribute.HasRoles(token, role)==false) { return MvcHtmlString.Create(""); } } //添加属性 builder.MergeAttributes(dicAttrs); //添加样式 builder.AddCssClass(css); builder.SetInnerText(text); //输出控件 return MvcHtmlString.Create(HttpUtility.HtmlDecode(builder.ToString(TagRenderMode.Normal))); }