因此,我为我的目的编写了扩展方法,以使用 @Html.BeginForm/@Ajax.BeginForm(被 using 包围)的方式生成 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));
}
}
}