【问题标题】:Get value from input box in code behind从后面代码中的输入框获取值
【发布时间】:2013-10-15 02:57:45
【问题描述】:

这是我的 .aspx 页面中的代码,我正在为文本框使用自动完成功能。

<script type="text/javascript">
    $(document).ready(function () {
        SearchText();
    });
    function SearchText() {
        $(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Preferences.aspx/GetAutoCompleteData",
                    data: "{'Name':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    }
</script>


<table style="width:auto">
    <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="Please Type Student Name:"></asp:Label>
        </td>
        <td>
            <input type="text" id="txtSearch" class="autosuggest" />
            <asp:TextBox ID="TextBox1" runat="server" Text=txtsearch Visible="true" class="autosuggest"></asp:TextBox>
        </td>
        <td>
            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
        </td>
    </tr>
</table>

如果我把 runat="Server" 放进去

<input type="text" id="txtSearch" class="autosuggest" />

然后自动完成不起作用。表单标签用于母版页。

问题解决使用控件的name属性

源代码:

    <input type="text" name="_name"  />

    <asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" />

代码隐藏:

protected void btnShow_Click(object sender, EventArgs e)
 {
    string strValue = Page.Request.Form["_name"].ToString();
    Response.Write(strValue);
 }

参考:http://www.etechpulse.com/2013/02/get-html-input-controls-value-server.html

感谢大家的帮助。

【问题讨论】:

  • 你想在页面加载中调用它吗?并检查控制台是否有任何错误?
  • 您正在执行 ajax 操作。这不会重新呈现您的整个页面。您需要将响应值加载到控件中。

标签: c# javascript jquery asp.net


【解决方案1】:

如果您使用 MasterPage,则 ASP.net 将为每个控件自动生成一个名称并将其附加到您的控件中,为了获得您需要使用 JQuery ClientID 的控件的唯一 ID。

输入runat="server",但将您的 jquery 函数更改为(这将通过 ClientID 检索输入):

 function SearchText() {
        $("#<%=txtSearch.ClientID%>").autocomplete({

或者作为替代方案(DeeMac 建议)使用静态ClientIDMode

【讨论】:

  • 这也是一个可行的替代方案来研究使用静态 ClientIDMode msdn.microsoft.com/en-us/library/…
  • 感谢@DeeMac 会将其添加到我的答案中:)
  • @user2345661 在进行更改后发出警报,看看它是否触发?
【解决方案2】:

要获取表单文本框的值,需要使用服务器控件。

 <asp:TextBox ID="txtSearch" runat="server" ></asp:TextBox>

您还可以在服务器控件中添加 ClientIDMode="static" 以保持您的 id 完全相同,或者您可以使用$("#&lt;%=txtSearch.ClientID%&gt;") 来获取动态生成的 Id。

【讨论】:

  • 我无法让服务器控制与 class="autosuggest" 一起使用。
猜你喜欢
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多