2016-07-06 152 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()方法