Custom AjaxHelper extension, merging AjaxOptions

2019-05-15 20:30发布

问题:

I am building a customer ajaxhelper extension in order to create an Ajax.ActionImage(...) method (see code below).

What I don't know how to do is "merge" the AjaxOptions into my anchor href attribute. I could use ajax.ActionLink(...) but then I don't know how t build my image element inside the created MvcHtmlString.

Thanks in advance!

    <Extension()> _
    Public Function ActionImage(ByVal ajax As AjaxHelper, ByVal controller As String, ByVal action As String, ByVal routeValues As Object, ByVal AjaxOptions As Object, ByVal imagePath As String, ByVal alt As String, ByVal width As Integer, ByVal height As Integer) As MvcHtmlString

        Dim url = New UrlHelper(ajax.ViewContext.RequestContext)

        Dim imgHtml As String
        Dim anchorHtml As String
        Dim imgbuilder = New TagBuilder("img")

        imgbuilder.MergeAttribute("src", url.Content(imagePath))
        imgbuilder.MergeAttribute("alt", alt)
        imgbuilder.MergeAttribute("width", width)
        imgbuilder.MergeAttribute("height", height)
        imgHtml = imgbuilder.ToString(TagRenderMode.SelfClosing)

        Dim anchorBuilder = New TagBuilder("a")
        anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues))
        anchorBuilder.InnerHtml = imgHtml
        anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal)

        Return MvcHtmlString.Create(anchorHtml)

    End Function

回答1:

First, you need to change the type of the variable ajaxOptions to AjaxOptions (in the System.Web.Ajax namespace). Once you have done this, you can add the following to merge your ajaxOptions into your anchor tag:

If ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled Then
    anchorBuilder.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes())
End If

You do not want the options inside your href. The options must be part of the anchor tag, in order to be parsed correctly by jquery.unobtrusive-ajax.js.

counsellorben