2011-11-21 25 views
1

我創建了一個MVC擴展以自動將屬性應用於html輸入。這是所有預期的工作,但是如果我想添加一個CSS類到HTML輸入,它已經有一個CSS類的代碼炸彈,因爲屬性已經設置。MVC .net添加/編輯幫助文件的CSS類.TextBox擴展

繼承人我的代碼:

public static MvcHtmlString LockableTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes, bool locked)  
    { 
     RouteValueDictionary dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 
     if (locked) 
     { 
      dic.Add("readonly", "readonly"); 
      dic.Add("class", "field-locked"); 
     } 
     return helper.TextBox(name, value, dic); 
    } 

我叫它像這樣:

@Html.LockableTextBox("Initals", Model.Initals, new {}, Model.Locked) 

其工作,但這一呼籲沒有

@Html.LockableTextBox("Initals", Model.Initals, new {@Class="field"}, Model.Locked) 

我如何改變DIC。添加(「類」,「字段鎖定」)行,以便它將我的額外類添加到現有的類屬性?

回答

1

您可以像使用簡單的Dictionary一樣使用它。檢查你是否已經有這樣的密鑰,並將你的字符串附加到現有的值,否則添加新的。

public static MvcHtmlString LockableTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes, bool locked)  
    { 
     RouteValueDictionary dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 
     if (locked) 
     { 
      dic.Add("readonly", "readonly"); 
      if (dic.ContainsKey("class")) 
       dic["class"] += " field-locked"; 
      else 
       dic.Add("class", "field-locked"); 
     } 
     return helper.TextBox(name, value, dic); 
    }