0%

【MVC】擴充HtmlHelper

  • 第一個範例,讓ActionLink可以放HTML標籤進去
  • 首先我先在專案中建立一個資料夾,並且在裡面新增一個類別檔案
     [![](http://2.bp.blogspot.com/-NBhxVa8AExI/UYoHecX2TrI/AAAAAAAADIE/G9Hvt_r7t_4/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)](http://2.bp.blogspot.com/-NBhxVa8AExI/UYoHecX2TrI/AAAAAAAADIE/G9Hvt_r7t_4/s1600/%E6%9C%AA%E5%91%BD%E5%90%8D.png)*   ```csharp
    
    //將命名空間改成System.Web.Mvc.Html,使用前不用修改~/Views/Web.config
    namespace System.Web.Mvc.Html
    {
    public static class MyHtmlHelperExtensions
    {
      public static MvcHtmlString InsertHtmlTagActionLink(this AjaxHelper ajaxHelper,string linkText ,string actionName, string controllerName, AjaxOptions ajaxOptions)        {
          var lnk = ajaxHelper.ActionLink("[replaceme]", actionName, controllerName, ajaxOptions);
          return MvcHtmlString.Create(lnk.ToString().Replace("[replaceme]", linkText));
      }
    
    }
1
2
3
*   使用方式如下      ```csharp
@Ajax.InsertHtmlTagActionLink("<i class='icon-file'></i>"+@childFunction.funname, action, controller, new AjaxOptions { UpdateTargetId="BackStageBody" });

  • 第二個範例,將TextBoxFor固定塞入一個data-content的html屬性,並將值給這個屬性
  • ```csharp
    public static MvcHtmlString TextBoxFor_WithOriginData<TModel, TProp>(this HtmlHelper htmlHelper, Expression<Func<TModel, TProp>> expression,object HtmlAttributes = null){
    //透過AnonymousObjectToHtmlAttributes將HtmlAttribute讀取出來
    var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlAttributes);
    //將expression的值抓出來放到data-content這個屬性中
    attrs.Add(“data-content”,ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model);
    var txtBoxFor = htmlHelper.TextBoxFor(expression, attrs);
    return MvcHtmlString.Create(txtBoxFor.ToString());
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
*   **第三個範例,加入Img這個Tag**
* ```csharp
public static MvcHtmlString ImageFor_WithOriginData<TModel, TProp>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProp>> expression, object HtmlAttributes = null){
string value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model == null ? "" : ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString();
//屬性的值
string propname = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;

//透過AnonymousObjectToHtmlAttributes將HtmlAttribute讀取出來
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlAttributes);
attrs.Add("data-content", value);
attrs.Add("src", value);
attrs.Add("name", propname);

var img = new TagBuilder("img");
img.MergeAttributes(attrs);
return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}