![](/img/trans.png)
[英]ASP.NET MVC4 - Different routing for 2 controllers with actionLinks
[英]ASP MVC ActionLinks with HTML content
有很好的擴展方法可以在ASP MVC中生成ActionLinks / RouteLinks。 但是,它僅允許您在生成的標記內編寫純文本。 如果要生成帶有圖像的錨點怎么辦?
我想使用引導程序中的圖標創建鏈接:
// expected result
<a href="/Customer?page=1"><i class="glyphicon glyphicon-arrow-left"></i> Previous page</a>
當您想生成簡單鏈接時,可以使用@ Url.Action(),如下所示:
<a href="@Url.Action("Index","Customer", new{ page = 1 })"><i class="glyphicon glyphicon-arrow-left"></i> Previous page</a>
但是,當您要生成Ajax鏈接時,它並不是那么簡單。 因為@ Ajax.ActionLink會使用由jquery-unobtrusive-ajax-min.js庫處理的javascript或“ data- *”屬性生成錨。
因此,我為自己的目的編寫了擴展方法,以使用@ Html.BeginForm / @ Ajax.BeginForm(使用包圍)的方式生成ActionLinks / RouteLinks。
用法:
// instead
@Html.ActionLink("Previous page", "Index", "Customer", new { page = 1 })
// you can write
@using(Html.BeginActionLink("Index", "Customer", new { page = 1 }) {
<text><i class="glyphicon glyphicon-arrow-left"></i> Previous page</text>
}
// same with ajax links
@using(Ajax.BeginActionLink("Index", new { page = 1 }, new AjaxOptions { ... }) {
<text><i class="glyphicon glyphicon-arrow-left"></i> Previous page</text>
}
方法BeginActionLink返回實現IDisposable的MvcLink類的實例。 在構造函數中,它寫入開始標簽,而在處置時,它寫入結束標簽。 大括號之間有您的代碼的位置
namespace System.Web.Mvc
{
using System.Text.RegularExpressions;
public class MvcLink : IDisposable
{
internal static readonly string InnerText = "___F7ED35E0097945398D5A969F8DE2C63C___";
private static readonly Regex RegexPattern = new Regex(@"^\s*(?<startTag>.*)\s*" + InnerText + @"\s*(?<endTag>.*)\s*$", RegexOptions.Compiled | RegexOptions.Singleline);
private readonly ViewContext _viewContext;
private readonly string _endTag;
internal MvcLink(ViewContext viewContext, IHtmlString actionLink) {
_viewContext = viewContext;
var match = RegexPattern.Match(actionLink.ToHtmlString());
if (match.Success) {
var startTag = match.Groups["startTag"].Value;
_endTag = match.Groups["endTag"].Value;
_viewContext.Writer.Write(startTag);
}
}
public void Dispose() {
_viewContext.Writer.Write(_endTag);
}
}
}
然后由您來編寫HtmlHelper和AjaxHelper的擴展方法。 方法ActionLink / RouteLink的重載過多,因此我只准備了我在應用程序中確實使用的重載。
但是寫其他東西很容易。 您可以看到我創建了MvcLink的實例,它將ViewContext作為第一個參數,並將內置ActionLink的結果與預定義的InnerText替換為您的內容。
namespace System.Web.Mvc
{
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
public static class MvcHelperExtensions
{
public static MvcLink BeginActionLink(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {
return new MvcLink(ajaxHelper.ViewContext, ajaxHelper.ActionLink(MvcLink.InnerText, actionName, routeValues, ajaxOptions, htmlAttributes));
}
public static MvcLink BeginActionLink(this HtmlHelper htmlHelper, string actionName, object routeValues, object htmlAttributes) {
return new MvcLink(htmlHelper.ViewContext, htmlHelper.ActionLink(MvcLink.InnerText, actionName, routeValues, htmlAttributes));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.