2011-06-29 79 views
3

我正在構建客戶ajaxhelper擴展以創建Ajax.ActionImage(...)方法(請參閱下面的代碼)。自定義AjaxHelper擴展,合併AjaxOptions

我不知道該怎麼做是將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 

回答

3

首先,你需要改變變量ajaxOptions到AjaxOptions類型(在System.Web.Ajax命名空間)。一旦你做到了這一點,你可以添加以下到您的ajaxOptions合併到您的錨標記:

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

你不希望您的href裏面的選項。選項必須是錨標記的一部分,才能被jquery.unobtrusive-ajax.js正確解析。

counsellorben

+0

這是完美的,我剛剛在谷歌上偶然發現了你在打字時的感受。非常感謝! –

+0

非常感謝!我之前看到了一個本Finkel試圖做的例子,但他們從未將IMG的東西添加到AJAX標記中,即使他們構建了它。我已經爲基本的HTML做了這個,但被困在同一個步驟。 – krillgar