0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

カスタムHtmlHelperの作り方メモ

Posted at

TagBuilderを使用しないカスタムHtmlHelperの書き方を忘れそうなのでメモ。

環境は以下

  • Visual Studio 2019
  • .NET Framework 4.7.2

[カスタムHtmlHelperクラスの定義部分]

実際に内部で呼び出されるのは従来のHtmlHelper。

Helper.cs

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;

namespace HtmlHelperTest.Models
{
    public static class Helper
    {
        public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>
                (this HtmlHelper<TModel> helper
                , Expression<Func<TModel, TProperty>> expression)
        {
            var htmlAttributes = new Dictionary<string, object>();
            // アトリビュートの追加
            htmlAttributes.Add("class", "custom");
            htmlAttributes.Add("style", "background-color: #00ff7f");

            return InputExtensions.TextBoxFor<TModel, TProperty>(helper, expression, htmlAttributes);
        }
    }
}


[View(.cshtml)]

書き方は従来のHtmlHelperと同じ。
カスタムHtmlHelperを定義したクラスのnamespaceの読み込みを忘れずに。

Index.cshtml
<!--ヘルパークラスのnamespace読み込み -->
@using HtmlHelperTest.Models

<!-- プロパティの読み込み -->
@model HtmlHelperTest.ViewModels.HelperViewModel

@using (@Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div>
        <div>
            @Html.LabelFor(model => model.TmpProperty)
        </div>
        <div>
            <!-- 定義したカスタムHtmlHelper -->
            @Html.CustomTextBoxFor(model => model.TmpProperty)
        </div>
    </div>
}

[Property]

HelperViewModel.cs
using System.ComponentModel.DataAnnotations;

namespace HtmlHelperTest.ViewModels
{
    public class HelperViewModel
    {
        [Display(Name = "サンプルプロパティ")]
        public string TmpProperty { get; set; }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?