开发者

NavigateUrl="#" becomes href="SubFolder/#"?

This isn't exactly Fermat's last theorem, but it keeps coming back to annoy me like an unpaid phone bill from college. Sometimes I want to create a HyperLink that does not cause a postback, so I want the target url to be #. When the markup happens to be from a UserControl in a subfolder,

/
|- Home.aspx (uses UC.ascx)
|- Sub
   |- UC.ascx
开发者_如何学编程

the URL is rewritten with a relative path, e.g.

<asp:HyperLink runat="server" NavigateUrl="#" >Click Me!</asp:HyperLink>

becomes

<a href="SubFolder/#">Click Me!</a>

Which is, unfortunately, wrong. Obviously I can get around this by not using a server control, but it seems stupid. Can this be avoided?

The point here is I will add a click event with jQuery or in code-behind, and I never want it to cause a postback, but I want it to be a hyperlink for CSS reasons.


easy way:

 <asp:HyperLink ID="HyperLink1" 
                navigateUrl="#" 
                onclick="javascript:return false;"                   
                runat="server">HyperLink</asp:HyperLink>

or

 <asp:HyperLink ID="HyperLink1" 
                href="#" 
                runat="server">HyperLink</asp:HyperLink>

or jquery add a class to the link you don't want to have a postback (nopostback) :

$("a.nopostback").bind('click', function () {
     return false;
})


You can set attributes for server-side elements.

<asp:HyperLink ID="HyperLink1" runat="server" Text="Click me"
    href="#" style="color: red;" />

In the code-behind as well, using Attributes property

HyperLink1.Attributes


Actually, adding the control to the page without the href/NavigateUrl attribute(s) offers the greatest flexiblity.

<asp:HyperLink ID="HyperLink1" runat="server"/>

Then assigning the href attribute in your code behind looks like Bruno's answer:

HyperLink1.Attributes.Add("href","{your-value-here}");

Though, Bruno and Caspar's answers work they break in certain contexts. For example, say your HyperLink control is nested in a Repeater. If you then wanted to conditionally set the href attribute to an actual URL or '#' those approaches will not work. The '#' will be rendered every time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜