开发者

How to Create a Friendly URL in a CS File

I know how to create a url by using html.actionlink in the aspx file. But if I want to create the same url in a code behind file how would I do th开发者_如何学Goat?


The code behind idea for views in MVC was removed coz it didn't really seem to fit the MVC paradigm. Maybe you should consider creating your own Html Helpers instead. Doing this, extending existing actions like Html.ActionLink() is easy (and heaps of fun).

This example shows how i created a helper to tweak my login/logout links. Some ppl might argue whether this is a good use for a helper but it works for me:

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

..and this is how i use it in the view (partial view to be exact):

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


Take a look at this post by Scott Mitchell

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

(Since you say 'html.actionlink' which is an instance of the UrlHelper class I am assuming you are in a context where you don't have access to an instance of the UrlHelper class)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜