拡張メソッドの定義方法
Moduleに記述する
Public修飾子を付ける
リスト4-37
Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Web.WebPages
Public Module MyHelperExtention 'モジュール名は任意
<Extension()>
Function Image(ByVal helper As HtmlHelper, ByVal src As String, ByVal alt As String) As IHtmlString
Return MvcHtmlString.Create(
String.Format("<img src=""{0}"" alt=""{1}"" />",
HttpUtility.HtmlAttributeEncode(UrlHelper.GenerateContentUrl(src, helper.ViewContext.HttpContext)),
HttpUtility.HtmlAttributeEncode(alt)))
End Function
<Extension()>
Function Video(ByVal helper As HtmlHelper, ByVal src As String, ByVal htmlAttrs As Object) As IHtmlString
Dim builder As New TagBuilder("video")
builder.MergeAttribute("src",
UrlHelper.GenerateContentUrl(src, helper.ViewContext.HttpContext))
builder.MergeAttribute("controls", "controls")
builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttrs))
Return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal))
End Function
<Extension()>
Function RadioButtonListFor(Of TModel, TProperty)(
helper As HtmlHelper(Of TModel),
exp As Expression(Of Func(Of TModel, TProperty)),
list As IEnumerable(Of SelectListItem),
htmlAtrrs As Object) As IHtmlString
Dim sb As New StringBuilder()
Dim name = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(exp))
Dim value = ModelMetadata.FromLambdaExpression(exp, helper.ViewData).Model.ToString()
Dim i As Integer = 1
For Each item In list
Dim id = String.Format("{0}_{1}", name, i)
i += 1
Dim label As New TagBuilder("label")
label.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAtrrs))
label.InnerHtml = helper.RadioButton(name, item.Value, (item.Value = value), New With {.id = id}).ToString
label.InnerHtml &= item.Text
sb.Append(label.ToString(TagRenderMode.Normal))
Next
Return MvcHtmlString.Create(sb.ToString())
End Function
<Extension()>
Function TemplateMessage(helper As HtmlHelper, template As Func(Of String, HelperResult), message As String) As IHtmlString
Return template(message)
End Function
End Module