asp.net-mvc - 如何从自定义帮助程序中使用 ASP.NET MVC Html 帮助程序?

标签 asp.net-mvc

我有几个页面列出了搜索结果,对于我想显示的每个结果我想创建一个自定义 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/

相关文章:

c# - 为什么 View 模型为空?

jquery - 单击按钮后在跨度文本中插入模型字符串

c# - 在编辑器 onload 中显示 Datepicker 而不是需要用户选择

URL 中的 ASP.NET 空格或 %20

asp.net-mvc - 是否可以跨 ASP.NET MVC 框架覆盖 UrlHelper.GenerateUrl()?

jquery - 如何根据服务器端决策有条件地运行 jQuery

asp.net-mvc - 验证 mvc 页面中隐藏字段的最佳方法是什么?

asp.net-mvc - MVC View 渲染不尊重 View 模型中传递的数据

asp.net-mvc - 如何删除有关 glyphicons-halflings-regular.woff2 未找到的错误

asp.net-mvc - Blazor WASM 页面路由