图像按钮 Ajax.ActionLink.
本文关键字:ActionLink Ajax 按钮 图像 | 更新日期: 2023-09-27 17:55:39
我正在尝试创建Ajax.ActionLink
的扩展。我已经对Html.ActionLink
及其工作做了同样的事情,但是当我尝试扩展 Ajax 方法时,它不起作用。发生的情况是,当我单击链接时,它不会呈现我的部分视图(替换),而是将我重定向到视图。我想指出搁浅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-*
属性,而另一个则不使用。我不确定如何解决这个问题。
您需要使用 .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()
方法的源代码