如何从一个自定义的助手使用ASP.NET MVC HTML辅助? [英] How to use ASP.NET MVC Html Helpers from a custom helper?

查看:83
本文介绍了如何从一个自定义的助手使用ASP.NET MVC HTML辅助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几页列出搜索结果,每个结果,我想展示我想,以避免重复显示code创建一个自定义视图助手。

I have several pages listing search results, for each result I would like to display I want to create a custom View Helper in order to avoid duplicating the display code.

我如何从我的自定义视图助手来访问便捷现有视图助手?即在我的自定义视图助手我想用Url.Action(),Html.ActionLink,等我如何从我的自定义视图助手访问它们?

How do I access the convenient existing view helpers from my custom view helper? I.e. in my custom view helper I would like to use Url.Action(), Html.ActionLink, etc. How do I access them from my custom view helper?

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;
        }
    }
}

使用System.Web.Mvc 允许访问 HtmlHelpers ,但像ActionLink的便捷方法非似乎是present。

using System.Web.Mvc gives access to HtmlHelpers, but non of the convenient methods like ActionLink seem to be present.

推荐答案

这个例子可以帮助你。这个辅助渲染取决于用户是否或没有登录不同的链接文字。它表明我的自定义助手内使用的ActionLink的:

This example should help you. This helper renders different link text depending on whether the user is logged in or not. It demonstrates the use of ActionLink inside my custom helper:

    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()的方法是替换此的HtmlHelper助手参数与像此UrlHelper urlHelp ,然后就叫 urlHelp.Action(...


All you would need to do to to access the Url.Action() method would be to replace the this HtmlHelper helper param with something like this UrlHelper urlHelp and then just call urlHelp.Action(...

希望这有助于。

这篇关于如何从一个自定义的助手使用ASP.NET MVC HTML辅助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆