@helper内で拡張メソッドの~For系を使いたい(2/2)

前のタイトルに(1/2)なんて書いたから、この投稿で(2/2)にして、おしまいにするしかないっすね。

さて、次のとあるモデルの項目なんすが、

    [Display(Name = "国名")]
    [MaxLength(100)]
    [Required]
    public string CountryName { get; set; }

このモデルのViewをEditでスキャフォールドしたコードは、こうなります。

<div class="form-group">
    @Html.LabelFor(model => model.CountryName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.CountryName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.CountryName, "", new { @class = "text-danger" })
    </div>
</div>

んで、ブラウザ表示がこんな感じ・・・

f:id:megusuritan:20171121225828j:plain

まぁ、十数項目くらいまでのモデルならいいんですがぁ。

これが、100個あったら?・・・Viewに示したのコードが100個できあがるわけですな。

作ってくれたコードで表示されたものが、このままでおkであれば、ここでおしまいなんですが・・・無情にもユーザーさんが「これ、もうちょっと右ぃ・・」とか、「色を赤にしてくんないかな」なんて言われたあかつきには・・・

同じことを100回コピペーしなきゃいかんのですわ。

もちょっと複雑なこと言われたら、やっとれんぎゃーこんなこと!ってなるんです・・・僕の場合・・・

ということで、@helper使えないんで、ヘルパーをC#で作っちゃえーなのです。

上のViewのコードを1行で済むようなヘルパーを作ります。

まずは、プロジェクトにHelpersフォルダを作ります。

その中に、EditHelpers.csとかなんでもいいんでC#コードファイル作ります。

こんな感じ・・・

f:id:megusuritan:20171121231908j:plain

コードファイルをこんな風にしますよ・・・

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

namespace Megsuritan.Helpers
{
    public static class EditHelpers
    {
        public static MvcHtmlString EditCountries<TModel, TValue>(this HtmlHelper helper, Expression<Func<TModel, TValue>> expression)
        {
            // @Html.LabelFor(model => model.CountryName, htmlAttributes: new { @class = "control-label col-md-2" })
            string line = helper.LabelFor(expression, htmlAttributes: new { @class = "control-label col-md-2" }).ToHtmlString();

            // <div class="col-md-10">
            TagBuilder tagColMd10 = new TagBuilder("div");
            tagColMd10.AddCssClass("col-md-10");

            //    @Html.EditorFor(model => model.CountryName, new { htmlAttributes = new { @class = "form-control" } })
            tagColMd10.InnerHtml = helper.EditorFor(expression, new { htmlAttributes = new { @class = "form-control" } }).ToHtmlString();

            //    @Html.ValidationMessageFor(model => model.CountryName, "", new { @class = "text-danger" })
            tagColMd10.InnerHtml += helper.ValidationMessageFor(expression, "", new { @class = "text-danger" }).ToHtmlString();

            // </div>
            line += tagColMd10.ToString();

            return MvcHtmlString.Create(line);
        }
    }
}

Viewで使うときは、コードの頭に

@using Megusuritan.Helpers

をつけて、該当のコード部分を次のように変更します。

@Html.EditCountries(modelItem => modelItem.CountryName)

これで、1行になりました。

「赤にして・・・」なんて、ヘルパーの中身を変えれば100個項目あっても怖くないじょ。

 

おしまい