【问题标题】:How to write <%%> in server controls?如何在服务器控件中编写 <%%>?
【发布时间】:2013-02-04 01:14:17
【问题描述】:

我正在尝试在服务器控件中使用&lt;%=%&gt;,但它不起作用。
这是我的代码:

 <input type="button" runat="server" value="<< Previous" id="btnPrevious" 
        onclick="location.href='<%=PreviousLink %>'"/>

PreviousLink 是页面中定义的属性。
当我查看页面时,整个表达式都是按原样编写的。

【问题讨论】:

    标签: c# asp.net .net asp.net-4.0


    【解决方案1】:

    你不能。您可以在控制器代码中定义它:

    btnPrevious.OnClientClick = "location.href='" + PreviousLink + "'"
    

    【讨论】:

    • 正是……你明白了。
    【解决方案2】:

    试试这个:

    使用 jQuery:

    <input type="button" runat="server" value="<< Previous" id="btnPrevious"/>
    <script>
    $(function () {
                $("#<%=btnPrevious.ClientID%>").on("click", function (event) {
                    window.location.href = '<%=PreviousLink %>';
                });
    });
    </script>
    

    使用 JavaScript:

    function onButtonClick() {
            window.location.href = '<%=PreviousLink %>';
        }
    
    <input type="button" runat="server" value="<< Previous" id="btnPrevious" onclick="onButtonClick();"/>
    

    .aspx.cs(C#代码):

    public string PreviousLink = "http://stackoverflow.com/";
    

    【讨论】:

      【解决方案3】:

      如果您删除 runat server 属性,则 表达式将得到正确评估。
      检查这个问题
      Why will <%= %> expressions as property values on a server-controls lead to a compile errors?

      【讨论】:

        【解决方案4】:

        这也应该有效:

        <script type="text/javascript">
        function setLocation() {
          location.href = '<%=PreviousLink %>';
        }
        </script>
        <input type="button" runat="server" value="<< Previous" id="btnPrevious" onclick="setLocation();"/>
        

        【讨论】:

          【解决方案5】:

          您可以做的是使用 ASP.NET 内联表达式在页面加载期间设置值。

          首先,在页面的代码隐藏中添加一个属性。

          protected string InputValue { get; set; }
          

          Page_Load事件中,设置属性值。

          protected void Page_Load(object sender, EventArgs e)
          {
              if (!Page.IsPostBack)
              {
                  this.InputValue = "something";
              }
          }
          

          最后,在页面标记中添加一个内联表达式,如下所示:

          <input type="text" name="txt" value="<%= this.InputValue %>" />
          

          这将允许您设置 input 元素的值,而无需使其成为服务器端标记。

          【讨论】:

            猜你喜欢
            • 2023-03-13
            • 2011-07-09
            • 1970-01-01
            • 1970-01-01
            • 2011-11-01
            • 2014-08-20
            • 2011-03-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多