2014-10-07 14 views
5

我有一个自定义助手:如何,我收到htmlAttributes作为参数合并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参数接收到“新{@class =”形式 - 控制“}”:

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

注意,“类”是正确显示,但其他人的扩展帮助属性是一个字典,什么是我做错了?

如果可能的话,我想只改变扩展帮助,而不是编辑模板,所以我觉得RouteValueDictionary传给EditorFor需要转换到一个匿名对象...

+0

https://cpratt.co/html-editorfor-and-htmlattributes/ – 2017-05-13 05:13:53

回答

4

我解决了,现在改变了我所有的编辑器模板行:

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; 
} 
-1
public static class CustomHelper 
    { 
     public static MvcHtmlString Custom(this HtmlHelper helper, string tagBuilder, object htmlAttributes) 
     { 
      var builder = new TagBuilder(tagBuilder); 

      RouteValueDictionary customAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 

      foreach (KeyValuePair<string, object> customAttribute in customAttributes) 
      { 
       builder.MergeAttribute(customAttribute.Key.ToString(), customAttribute.Value.ToString()); 
      } 

      return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); 
     } 
    } 
+1

您应该解释如何解决他的问题 – adao7000 2015-07-07 14:11:09

相关问题