2016-07-06 138 views
-1

我想創建一個Ajax.ActionLink的擴展。我已經做了Html.ActionLink和它的工作,但是當我試圖使Ajax方法的擴展,它不工作。發生什麼事是,當我點擊鏈接時,它不會呈現我的部分視圖(替換),而是將其重定向到視圖。我想指出,擱淺Ajax.ActionLink方法是工作的罰款圖像按鈕Ajax.ActionLink

這裏是我的代碼:

public static IHtmlString ImageActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, 
    object routeValues, object linkHtmlAttributes, AjaxOptions ajaxOptions, string imageSrc, object imageHtmlAttributes) 
{ 
    UrlHelper urlHelper = new UrlHelper(ajaxHelper.ViewContext.RequestContext); 

    //Image tag 
    TagBuilder imageTag = new TagBuilder("img"); 
    imageTag.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc)); 
    imageTag.MergeAttributes(new RouteValueDictionary(imageHtmlAttributes), false); 

    //Anchor tag 
    TagBuilder anchorTag = new TagBuilder("a"); 
    anchorTag.InnerHtml = imageTag.ToString(TagRenderMode.SelfClosing); 
    anchorTag.Attributes.Add("href", urlHelper.Action(actionName, controllerName, routeValues)); 
    anchorTag.MergeAttributes(new RouteValueDictionary(ajaxOptions), false); 
    anchorTag.MergeAttributes(new RouteValueDictionary(linkHtmlAttributes), false); 

    return MvcHtmlString.Create(anchorTag.ToString()); 
} 

我試圖調試的問題,所以我比較無論是從正常和擴展生成的HTML方法:

正常(工作):

<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#Edit" href="/Admin/Event/Edit/1">Edit</a> 

擴展:

<a allowcache="False" confirm="" httpmethod="" insertionmode="Replace" loadingelementduration="0" loadingelementid="" onbegin="" oncomplete="" onfailure="" onsuccess="" updatetargetid="Edit" url="" href="/Admin/Event/Edit/1"><img src="/Content/Images/edit-icon.png"></a> 

呈現的Html是不同的,因爲正常的方法使用Html data-*屬性,而另一個不是。我不知道如何解決這個問題。

回答

0

您需要使用.ToUnobtrusiveHtmlAttributes()方法AjaxOptions來生成正確的data-ajax-*屬性。你的方法應該是

public static IHtmlString ImageActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, 
    object routeValues, object linkHtmlAttributes, AjaxOptions ajaxOptions, string imageSrc, object imageHtmlAttributes) 
{ 
    UrlHelper urlHelper = new UrlHelper(ajaxHelper.ViewContext.RequestContext); 

    //Image tag 
    TagBuilder imageTag = new TagBuilder("img"); 
    imageTag.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc)); 
    imageTag.MergeAttributes(new RouteValueDictionary(imageHtmlAttributes), false); 

    //Anchor tag 
    TagBuilder anchorTag = new TagBuilder("a"); 
    anchorTag.InnerHtml = imageTag.ToString(TagRenderMode.SelfClosing); 
    anchorTag.Attributes.Add("href", urlHelper.Action(actionName, controllerName, routeValues)); 

    // change the following line 
    anchorTag.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes()); 
    // recommend the following change 
    anchorTag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(linkHtmlAttributes))); 

    return MvcHtmlString.Create(anchorTag.ToString()); 
} 

邊注:參見source code.ToUnobtrusiveHtmlAttributes()方法