2009-09-06 52 views
0

O.K.我认为这很简单!
我有一个ViewMasterPage的一些链接(首页/关于/登录/等)。我想要实现的只是当链接已被打开时链接被禁用(即,如果当前网址是/ Register,那么注册链接应该被禁用..容易啊!?)
因为我不喜欢在我的视图中编写大量的内联编码,最后我用一些扩展方法(只是为了将代码保存在.cs文件中)扩展HtmlHelper,并在我的视图中调用这些方法,下面是我的注册方法:
禁用当前网址的链接?

public static string Register (this HtmlHelper html) 
    { 
     TagBuilder builder ; 
     if (HttpContext.Current.Request.Url.AbsoluteUri.ToUpperInvariant().Contains(MainLinks.Register.ToUpperInvariant())) 
      return MainLinks.Register; // will return the string "Register" 

     builder = new TagBuilder("a"); 
     builder.InnerHtml = MainLinks.Register; 
     builder.AddCssClass("register"); 
     builder.Attributes.Add("href", "/register/"); 
     return builder.ToString(); 
    } 

虽然这个工作,它仍然有两个问题:

  1. URL的硬编码字符串值(专门为家乡链路,因为我比较AbslouteUri与“http://www.mysite.com/”)

  2. 我的编程本能不喜欢它,我觉得它应该是比简单得多。

任何想法!


Ps:不允许javascipt!这是一个无JavaScript版本的应用程序。

回答

1

我没有看到太多的错误,很明显看到它的功能和工作原理。不过,让它更具可重用性可能会更好,因为我可以想象你会用其他链接重复一下自己。也许是这样的:

public static string RenderLink(this HtmlHelper html, string text, string url, object htmlAttr) { 
    if (!HttpContext.Current.Request.Url.AbsolutePath.StartsWith(url, StringComparison.InvariantCultureIgnoreCase)) { 
    return text; //comparison excludes the domain 
    } 
    TagBuilder tag = new TagBuilder("a"); 
    tag.SetInnerText(text); 
    tag.Attributes.Add("href", url); 
    //... add attributes parsed as htmlAttr here 
    return tag.ToString(); 
} 

添加您的链接到你的观点一样:

<%= Html.RenderLink("Register", "/register/", new { @class="register"}) %> 
<%= Html.RenderLink("Account", "/account/", new { @class="account"}) %> 

如果你想从硬编码的域了,然后用Request.Url.AbsolutePath代替AbsoluteUri如上所述达到此目的。

另一种方法是从控制器解析模型中的当前页面信息,可能类似于ViewData.Model.CurrentPage =“Register”;,但我不会建议你这样做,因为在这种情况下我没有看到它是控制器的工作。

+0

谢谢DaveG!我会尽量保持干爽!我会在这里等一段时间,也许有人提出一个更简单的想法!再次感谢。 – Galilyou 2009-09-07 06:50:19

+0

哦,我几乎忘了提及它.. +1 :) – Galilyou 2009-09-07 06:51:07