【问题标题】:hyperlink.NavigateUrl getting changed on master page (possibly by ResolveUrl() )hyperlink.NavigateUrl 在母版页上被更改(可能由 ResolveUrl() )
【发布时间】:2011-06-24 03:06:25
【问题描述】:

我有一个超链接,在某些情况下我想更改它以显示 jquery 弹出窗口,但在母版页上执行此操作时遇到了一个奇怪的问题。以下内容适用于常规页面:

hyp1.NavigateUrl = "#notificationPopup";

呈现为:

<a id="ctl00_hyp1" href="#notificationPopup">Example</a>

这正是我想要的。问题在于它呈现为的母版页上的超链接上的代码完全相同:

<a id="ctl00_hyp1" href="../MasterPages/#notificationPopup">Example</a>

当我在母版页上设置它时,它看起来可能正在通过 ResolveClientUrl() 或其他方式运行 navigateUrl。我尝试将&lt;asp:hyperlink 换成&lt;a href runat=server,但同样的事情发生了。

有什么想法吗?

【问题讨论】:

    标签: asp.net hyperlink master-pages resolveurl


    【解决方案1】:

    MSDN 上有注释Control.ResolveClientUrl 方法说明。

    这个方法返回的网址是 相对于包含 控件所在的源文件 实例化。继承的控件 此属性,例如 UserControl 和 MasterPage,将返回一个完整的 相对于控件的限定 URL。

    因此,您的示例中母版页的行为是完全可以预测的(尽管使用起来不太舒服)。那么有哪些替代方案呢?

    最好将&lt;a&gt;设置为客户端控件(去掉runat="server");即使在母版页中也应该像魅力一样工作:

    <a href="#notificationPopup">Example</a>
    

    如果此控件应仅用于服务器端:您可以使用 UriBuilder 类从后面的代码构建一个 URL:

    UriBuilder newPath = new UriBuilder(Request.Url);
    // this will add a #notificationPopup fragment to the current URL
    newPath.Fragment = "notificationPopup";
    hyp1.HRef = newPath.Uri.ToString();
    

    【讨论】:

    • 为重建完整 URL 的想法喝彩。使用实际 URL +“#notificationPopup”对弹出窗口效果很好,所以我选择了:Request.Url.ToString() + "#notificationPopup";,因为它更简单
    【解决方案2】:

    在您的表单上创建一个隐藏字段并将值设置为您要导航的位置/超链接的 url 而不是超链接导航 url。然后在 javascript 中调用超链接的 onclick 方法,并在浏览器进行实际导航之前将超链接设置在那里。

    <html><head><title></title></head>
    <script type="text/javascript">
    
    function navHyperlink(field)
    {
    field.href = document.getElementById('ctl00_hdnHypNav').value;
    return true;
    }
    
    </script>
    <input type="hidden" id="hdnHypNav" value="test2.html" runat="server"/>
        <a href="" onclick="navHyperlink(this);" >click here</a>
    </html>
    

    后面的代码是: hdnHypNav.value = "#notificationPopup";

    您也可以尝试在回发后使用以下代码设置 url,即将您的代码替换为下面的代码,但我不确定它是否会起作用...

    ScriptManager.RegisterStartupScript(this,this.GetType(),"SetHyp","$('ctl00_hyp1').href = '#notificationPopup';",True)
    

    【讨论】:

      【解决方案3】:

      我找到了解决问题的另一种方法。

      hyp1.Attributes.Add("href", "#notificationPopup");
      

      【讨论】:

        【解决方案4】:

        看到我用runat="server" 替换静态超链接的全部原因是为了从基于资源的自动本地化中受益,但这些答案都不能满足我的需求。

        我的解决方法是将超链接括在文字中:

        <asp:Literal ID="lit1" runat="server" meta:resourcekey="lit1">
          <a href="#notificationPopup">Example</a>
        </asp:Literal>
        

        缺点是如果您需要以编程方式操作链接,那就有点烦人了:

        lit1.Text = String.Format("<a href=\"{0}\">Example</a>", HttpUtility.HtmlAttributeEncode(url));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-29
          • 1970-01-01
          • 2017-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多