图像按钮Ajax.ActionLink

时间:2016-07-06 22:04:22

标签: c# ajax asp.net-mvc

我正在尝试创建''的扩展名。我已经对Ajax.ActionLink和它的工作做了同样的事情但是当我试图扩展Ajax方法时,它不起作用。当我点击链接时,它不会渲染我的局部视图(替换),而是将我重定向到视图。我想要注意搁浅的Html.ActionLink方法工作正常

这是我的代码:

Ajax.ActionLink

我试图调试这个问题,所以我比较了普通方法和扩展方法生成的Html:

正常(工作):

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());
}

扩展:

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

呈现的Html是不同的,因为普通方法使用Html <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> 属性而另一个不使用。我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分: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());
}

附注:请.ToUnobtrusiveHtmlAttributes()方法

参考source code