如何在CS文件中创建友好URL

时间:2009-11-09 05:09:33

标签: c# asp.net-mvc

我知道如何在aspx文件中使用html.actionlink创建一个url。但是,如果我想在文件后面的代码中创建相同的URL,我该怎么做?

2 个答案:

答案 0 :(得分:1)

MVC中的视图背后的代码被删除了因为它似乎并不适合MVC范例。也许你应该考虑creating your own Html Helpers。这样做,扩展Html.ActionLink()等现有操作很容易(而且很有趣)。

此示例显示了我如何创建帮助程序以调整我的登录/注销链接。一些人可能会争辩这是否适合帮助者,但它对我有用:

    /// <summary>
    /// For the global MasterPage's footer
    /// </summary>
    /// <returns></returns>
    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);
    }

..这就是我在视图中使用它的方法(准确的部分视图):

<% =Html.FooterEditLink(HttpContext.Current.User.Identity, "Edit", "Logout (" + HttpContext.Current.User.Identity.Name + ")")%>

答案 1 :(得分:0)

看看Scott Mitchell的这篇文章

http://scottonwriting.net/sowblog/posts/14011.aspx

(因为您说'html.actionlink'是UrlHelper类的一个实例,我假设您处于无法访问UrlHelper类实例的上下文中)