自定义AjaxHelper扩展,合并AjaxOptions

时间:2011-06-29 18:57:49

标签: ajax asp.net-mvc-3

我正在构建一个客户ajaxhelper扩展,以便创建一个Ajax.ActionImage(...)方法(参见下面的代码)。

我不知道怎么做是将AjaxOptions“合并”到我的anchor href属性中。我可以使用ajax.ActionLink(...),但后来我不知道如何在创建的MvcHtmlString中构建我的图像元素。

提前致谢!

    <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 个答案:

答案 0 :(得分:3)

首先,您需要将变量ajaxOptions的类型更改为AjaxOptions(在System.Web.Ajax命名空间中)。完成此操作后,您可以添加以下内容以将ajaxOptions合并到锚标记中:

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

您不希望href中有选项。选项必须是锚标记的一部分,以便jquery.unobtrusive-ajax.js正确解析。

counsellorben