2014-10-07 22 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

相關問題