我有几个页面列出了搜索结果,对于我想显示的每个结果我想创建一个自定义 View Helper 以避免重复显示代码。
如何从我的自定义 View 助手中访问方便的现有 View 助手? IE。在我的自定义 View 助手中,我想使用 Url.Action()、Html.ActionLink 等。如何从自定义 View 助手中访问它们?
using System;
namespace MvcApp.Helpers
{
public class SearchResultHelper
{
public static string Show(Result result)
{
string str = "";
// producing HTML for search result here
// instead of writing
str += String.Format("<a href=\"/showresult/{0}\">{1}</a>", result.id, result.title);
// I would like to use Url.Action, Html.ActionLink, etc. How?
return str;
}
}
}
using System.Web.Mvc
允许访问 HtmlHelpers
,但似乎没有像 ActionLink 这样的方便方法。
最佳答案
这个例子应该对你有所帮助。这个助手根据用户是否登录来呈现不同的链接文本。它演示了在我的自定义助手中使用 ActionLink:
public static string FooterEditLink(this HtmlHelper helper,
System.Security.Principal.IIdentity user, string loginText, string logoutText)
{
if (user.IsAuthenticated)
return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, logoutText, "Logout", "Account",
new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
else
return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, loginText, "Login", "Account",
new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
}
编辑:
您需要做的就是访问
Url.Action()
方法是替换 this HtmlHelper helper
类似于 this UrlHelper urlHelp
的参数然后调用urlHelp.Action(...
希望这可以帮助。
关于asp.net-mvc - 如何从自定义帮助程序中使用 ASP.NET MVC Html 帮助程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/876670/