シンプルな拡張 †拡張メソッドを利用して、標準のHTMLHelperを拡張する。 C#コード: using System; using System.Web.Mvc; namespace MvcApplication1.Helpers { public static class LabelExtensions { public static string Label(this HtmlHelper helper, string target, string text) { return String.Format("<label for='{0}'>{1}</label>", target, text); } } } VBコード: Imports System.Runtime.CompilerServices Public Module LabelExtensions <Extension()> _ Public Function Label(ByVal helper As HtmlHelper, ByVal target As String, ByVal text As String) As String Return String.Format("<label for='{0}'> {1}</label>", target, text) End Function End Module HTML側に以下のように呼び出す: <%= Html.Label("lastName", "Last Name:") %> JavaScriptコード †TagBuilderを利用する方法 public static class HtmlExtensions { public static IHtmlString ExecuteCallback(this HtmlHelper helper, string callback) { var script = new TagBuilder("script"); script.Attributes["type"] = "text/javascript"; script.InnerHtml = string.Format("{0}();", callback); return new HtmlString(script.ToString(TagRenderMode.Normal)); } } HTML側に以下のように呼び出す: #codeprettify{{ @Html.ExecuteCallback("someCallback") 生成されたコード: <script type="text/javascript"> function someCallback() { alert('the callback is executed'); } </script> 文字列を利用する方法もある、単純に文字列を返す namespace MvcApplication1.ExtensionMethods { public static class MyExtensionMethods { public static MvcHtmlString SomeJavascript(this HtmlHelper helper) { StringBuilder sb = new StringBuilder(); sb.Append("<script> alert('testing 123')</script>"); return MvcHtmlString.Create(sb.ToString()); } } } HTML側に以下のように呼び出す: @using MvcApplication1.ExtensionMethods @Html.SomeJavascript() Model Binding †using System.Web.Mvc; public static MvcHtmlString CustomHelperFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { var fieldName = ExpressionHelper.GetExpressionText(expression); var fullBindingName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName); var fieldId = TagBuilder.CreateSanitizedId(fullBindingName); var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); var value = metadata.Model; TagBuilder tag = new TagBuilder("input"); tag.Attributes.Add("name", fullBindingName); tag.Attributes.Add("id", fieldId); tag.Attributes.Add("type", "text"); tag.Attributes.Add("value", value == null ? "" : value.ToString()); var validationAttributes = html.GetUnobtrusiveValidationAttributes(fullBindingName, metadata); foreach (var key in validationAttributes.Keys) { tag.Attributes.Add(key, validationAttributes[key].ToString()); } return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing)); } HTML側に以下のように呼び出す: @Html.CustomHelperFor(model => model.ParentDropDown.SelectedValue) 生成されたコード: <input id="ParentDropDown_SelectedValue" name="ParentDropDown.SelectedValue" type="text" value="4"> iディレクトリで複数のポータルサイトにディレクトリ登録 コメント: |