Help us understand the problem. What is going on with this article?

カスタムHtmlHelperの作り方メモ

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; }
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした