TextBox jQuery Popup with DataTable

时间:2016-12-29 16:20:27

标签: javascript c# jquery asp.net

我在ASP中动态构建了一个文本框,如下所示:

<form action="http://consumerlending/app/indirect/dealerComments.aspx?">
<input type="text" name="dealerCode"><input type="submit" value="GO"></form>

我希望将文本框中的值作为参数,从后面代码中的可数据函数中形成一系列行,并显示为用户可从中选择的选项列表。列表功能如下。

public List<JSON_Dealer> GetDealers()
        {
            ArrayList lst = new ArrayList();
            DataTable dt = getDealerInformation(dlrNum);

            List<JSON_Dealer> dealers = new List<JSON_Dealer>();
            JSON_Dealer dlr = default(JSON_Dealer);

            foreach (DataRow row in dt.Rows)
            {
                dlr = new JSON_Dealer();

                dlr.value = row.Field<int>("dealer_id");
                dlr.label = row.Field<string>("dlr");
                dealers.Add(dlr);
            }
            return dealers;
        }

我的JSON_Dealer类显示选项设置如下:

public class JSON_Dealer
{
    public int value;
    public string label;
}

在aspx页面上我有如下jQuery,但是当我在浏览器中运行代码时出错:

<script type="text/javascript">
            var hidDealers = '<%= hidDealers.ClientID %>';
            var hidSelectedDealer = '<%= hidSelectedDealer.ClientID %>';
            var hidSessionDealer = '<%= Session["dlrNum"] %>';
        </script>

        <script type="text/javascript">
        //finds querystring values
        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }

        // if querystring dlrnum has a value, the page will pre-load the contents
        var dlrNum = getParameterByName('dlrnum');
        if (dlrNum.length > 0) {

            //set textbox value
            $("#txtDlr").val(dlrNum);

            //get JSON value for intellisense
            var JSON_dlrs = $("#" + hidDealers).val();
            var dlrs = JSON.parse(JSON_dlrs);

            //loop through looking for requested dealer to prepopulate page
            for (var i = 0; i < dlrs.length; i++) {
                if (dlrs[i].value == dlrNum) {
                    //alert(dlrs[i].value);
                    SerializeDealer(hidSelectedDealer, dlrs[i]);
                    InitializeControls();
                    InitializeDealerInfo()
                    break;
                }
            }
        }
        else {
            //set textbox value
            $("#txtDlr").val(hidSessionDealer);

            //get JSON value for intellisense
            var JSON_dlrs = $("#" + hidDealers).val();
            var dlrs = JSON.parse(JSON_dlrs);

            //loop through looking for requested dealer to prepopulate page
            for (var i = 0; i < dlrs.length; i++) {
                if (dlrs[i].value == hidSessionDealer) {
                    SerializeDealer(hidSelectedDealer, dlrs[i]);
                    InitializeControls();
                    InitializeDealerInfo();
                    break;
                }
            }
        }

    </script>

我无法弄清楚出了什么问题,弹出搜索列表框肯定无法正常工作。以下是我遇到的错误:

Control 'hidDealers' of type 'HiddenField' must be placed inside a form tag with runat=server.

ASPX页码

<%@ Page Title="Dealer Services Hub" Language="C#"  AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="Hub._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <link rel="stylesheet" type="text/css" href="Content/dshubfinalmockup.css"/>
        <link rel="stylesheet" href="scripts/fontawesome/css/font-awesome.min.css"/>

        <!--jQuery Lightbox-->
        <link rel="stylesheet" href="styles/jquery-ui.css" />
        <script src="scripts/jquery-1.9.1.js" type="text/javascript"></script>
        <script src="scripts/jquery-ui.js" type="text/javascript"></script>
        <link rel="stylesheet" href="styles/colorbox.css" />
        <script src="scripts/jquery.colorbox-min.js" type="text/javascript"></script>

        <!--Modal Window-->
        <script type="text/javascript">

            $(document).ready(function () {
                $(".iframe").colorbox({ iframe: true, width: "900px", height: "300px" });
                $(".iframe.cboxElement").colorbox({ title: '' });
                $(".contacts").colorbox({ iframe: true, width: "600px", height: "600px" });
                $(".contacts.cboxElement").colorbox({ title: '' });                
            });

        </script>
        <%-- Auto complete for Dealer Number Search --%>
        <script type="text/javascript">
            var hidDealers = '<%= hidDealers.ClientID %>';
            var hidSelectedDealer = '<%= hidSelectedDealer.ClientID %>';
            var hidSessionDealer = '<%= Session["dlrNum"] %>';
        </script>

        <script type="text/javascript">
        //finds querystring values
        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }

        // if querystring dlrnum has a value, the page will pre-load the contents
        var dlrNum = getParameterByName('dlrnum');
        if (dlrNum.length > 0) {

            //set textbox value
            $("#txtDlr").val(dlrNum);

            //get JSON value for intellisense
            var JSON_dlrs = $("#" + hidDealers).val();
            var dlrs = JSON.parse(JSON_dlrs);

            //loop through looking for requested dealer to prepopulate page
            for (var i = 0; i < dlrs.length; i++) {
                if (dlrs[i].value == dlrNum) {
                    //alert(dlrs[i].value);
                    SerializeDealer(hidSelectedDealer, dlrs[i]);
                    InitializeControls();
                    InitializeDealerInfo()
                    break;
                }
            }
        }
        else {
            //set textbox value
            $("#txtDlr").val(hidSessionDealer);

            //get JSON value for intellisense
            var JSON_dlrs = $("#" + hidDealers).val();
            var dlrs = JSON.parse(JSON_dlrs);

            //loop through looking for requested dealer to prepopulate page
            for (var i = 0; i < dlrs.length; i++) {
                if (dlrs[i].value == hidSessionDealer) {
                    SerializeDealer(hidSelectedDealer, dlrs[i]);
                    InitializeControls();
                    InitializeDealerInfo();
                    break;
                }
            }
        }

    </script>

        <title>Dealer Services Hub</title>

    </head>

    <body>
        <div id="wrapper"> 
            <!--Header Div-->
            <div id="header">
                <div id="usbanklogo">
                    <img src="image/usbankLogo2.png" alt="US Bank Logo"/>
                </div>            

                <div id="dealerservicesdiv">DEALER SERVICES HUB</div>

                 <div id ="performanceanalyticscontact">

                    <%--<a class= "contacts" href= #contactpage title= "Contact Performance Analytics">--%>
                    <a class= "contacts cboxElement" href= "Contacts.aspx" title= "Contact Performance Analytics">
                        <i class="fa fa-phone-square fa-2x"></i>
                    </a>                

                     <!--<i class="fa fa-question-circle-o fa-2x"></i>-->

                    <asp:PlaceHolder ID = "utilities" runat="server">

                    </asp:PlaceHolder>

                 </div>                
            </div>

            <!--Body Div-->
            <div id="body">

                <div id = "maindiv">
                    <asp:PlaceHolder ID ="maindivs" runat="server">

                    </asp:PlaceHolder>
                </div>

                <div id = "sidebardiv">
                     <asp:PlaceHolder ID ="sidebardivs" runat="server">

                    </asp:PlaceHolder> 
                </div>                
            </div>

    <!--Footer Div-->
         <div id="footer">
             <a target="_blank" href="http://usbnetportal.us.bank-dns.com/USBToday/Default.aspx">
                <div>
                     <span>USBNet</span>
                </div>
             </a>

             <a target="_blank" href="https://vision.appreciatehub.com/ui/greatwork/index.html?locale=en_US&showCookieMsg=falsehttps://vision.appreciatehub.com/ui/greatwork/index.html?locale=en_US&showCookieMsg=false">         
                 <div>
                    <span>Best In Us</span>
                 </div>
              </a>

             <a target="_blank" href="https://directory.us.bank-dns.com/directory/index.action">           
                 <div>
                    <span>Directory</span>
                 </div>
             </a>   

         </div>

        </div>

        <%-- Hidden fields for list of dealers --%>
        <asp:HiddenField ID="hidDealers" runat="server"/>
        <asp:HiddenField ID="hidSelectedDealer" runat="server"  />
        <asp:HiddenField ID="hidSessionDealer" runat="server"  />
    </body>
</html>

背后的代码

public partial class _Default : Page
    {
        public string dlrNum;
        protected void Page_Load(object sender, EventArgs e){}
        protected override void OnLoad(EventArgs e)
        {
            if ((Request.QueryString["dlrNum"] != null))
            {
                dlrNum = Request.QueryString["dlrNum"];
                getDealerInformation(dlrNum);
            }

            if (User.IsInRole("DSAdmin"))
            {
                utilities.Visible = true;

            }
            else
            {
                utilities.Visible = false;
            }
            addmainDiv();
            addsideBarDiv();
            getUtilitiesInfo();
        }

        #region SQL DataTable functions

        private DataTable getHubCategoryData(int typeId)
        {
            string constr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("[Hub].[spgetHubCategoryLayout]"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("typeID", typeId));
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
        }

        private DataTable getFrequentLinks(string username)
        {
            string constr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("[Hub].[spgetFrequentVisits]"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("username", username));
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
        }


        private DataTable getDealerInformation(string dealerNum)
        {
            string constr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("[Hub].[spgetDealerListbyEntry]"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("prefixText", dealerNum));
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
        }

        //Addition JSON to load a list of dealers based on the dealer entry
        public List<JSON_Dealer> GetDealers()
        {
            ArrayList lst = new ArrayList();
            DataTable dt = getDealerInformation(dlrNum);

            List<JSON_Dealer> dealers = new List<JSON_Dealer>();
            JSON_Dealer dlr = default(JSON_Dealer);

            foreach (DataRow row in dt.Rows)
            {
                dlr = new JSON_Dealer();

                dlr.value = row.Field<int>("dealer_id");
                dlr.label = row.Field<string>("dlr");
                dealers.Add(dlr);
            }
            return dealers;
        }

        #endregion

        #region functions that manipulate SQL Data functions
        protected void addmainDiv()
        {
            DataTable dt = this.getHubCategoryData(1);
            StringBuilder html = new StringBuilder();

            foreach (DataRow row in dt.Rows)
            {
                string divCSSClass = row.Field<string>("divCSSClass");
                int categoryID =  row.Field<int>("categoryID");
                string href = "subCategories.aspx?categoryID=" + categoryID.ToString() + "";

                html.Append("<a class='iframe cboxElement' href=" + href + ">");

                html.Append("<div class = " + "'" + divCSSClass+ "'" + ">");

                    html.Append("<i class=" + "'" + row[dt.Columns["iconInfo"]] + " ");
                        html.Append(row[dt.Columns["iconSize"]] + "'></i><h2>" + row[dt.Columns["categoryName"]] + "</h2>");
                    html.Append("</div>");

                html.Append("</a>");

            }
            maindivs.Controls.Add(new Literal { Text = html.ToString() });
        }
        protected void addsideBarDiv()
        {
            DataTable dt = this.getHubCategoryData(2);
            StringBuilder html = new StringBuilder();

            foreach (DataRow row in dt.Rows)
            {
                string divCSSClass = row.Field<string>("divCSSClass");
                string categoryName = row.Field<string>("categoryName");

                //This is hard coded. I have to make this more dynamic
                if (categoryName == "Frequent Views")
                {
                    html.Append("<div class = " + "'" + divCSSClass + "'" + " div id = 'recentsdiv'>");
                        html.Append("<div id = 'recentlinkstitle'>");
                            html.Append("<i class=" + "' " + row[dt.Columns["iconInfo"]] + " ");
                            html.Append(row[dt.Columns["iconSize"]] + "'></i> " + row[dt.Columns["categoryName"]]);
                        html.Append("</div>");
                    html.Append(showFrequentLinksbyUser());
                    html.Append("</div>");
                }

                else if (categoryName == "Dealer Comments")
                {
                    html.Append("<div class = " + "'" + divCSSClass + "'" + " div id ='dealercommentsdiv'>");
                        html.Append("<i class=" + "'" + row[dt.Columns["iconInfo"]] + " ");
                        html.Append(row[dt.Columns["iconSize"]] + "'></i><h2>" + row[dt.Columns["categoryName"]] + "</h2>");
                        html.Append("<form action='http://consumerlending/app/indirect/dealerComments.aspx?'>");

                            html.Append("<input ID ='dlrNumText' type='text' name='dlrnum''>");
                            html.Append("<input ID = 'searchBtn' type='submit' value='GO'>");
                    //html.Append("<input ID ='dlrNumText' type='text' name=" + dlrNum + "'>");
                    //html.Append("<input ID = 'searchBtn' type='submit' value='GO'>");


                    html.Append("</form>");
                    html.Append("</div>");
                }
                else
                {
                    html.Append("<div class = " + "'" + divCSSClass + "'" + ">");
                    html.Append("<i class=" + "'" + row[dt.Columns["iconInfo"]] + " ");
                    html.Append(row[dt.Columns["iconSize"]] + "'></i><h2>" + row[dt.Columns["categoryName"]] + "</h2>");
                    html.Append("</div>");
                }
            }
            sidebardivs.Controls.Add(new Literal { Text = html.ToString() });
        }
        private void getUtilitiesInfo()
        {
            DataTable dt = this.getHubCategoryData(3);
            StringBuilder html = new StringBuilder();


            foreach (DataRow row in dt.Rows)
            {
                string title = row.Field<string>("categoryName");
                string iconinfo = row.Field<string>("iconInfo");
                string iconsize = row.Field<string>("iconSize");
                string divCSSClass = row.Field<string>("divCSSClass");

                int categoryID = row.Field<int>("categoryID");
                string href = "subCategories.aspx?categoryID=" + categoryID.ToString() + "";

                html.Append("<a class= 'iframe cboxElement' href =" + href + " title= '" + title + "'" + ">");
                html.Append("<i class='" + row[dt.Columns["iconInfo"]] + " " + row[dt.Columns["iconSize"]] + "'></i>");
                html.Append("</a>");
            }
            utilities.Controls.Add(new Literal { Text = html.ToString() });
        }
        private string showFrequentLinksbyUser()
        {
            DataTable dt = this.getFrequentLinks(Utility.cleanUsername(User.Identity.Name));
            StringBuilder html = new StringBuilder();

            html.Append("<div id = 'recentlinks'>");
            html.Append("<ol>");
            foreach (DataRow row in dt.Rows)
            {
                string name = row.Field<string>("reportName").Trim();
                string href = "http://consumerlending.us.bank-dns.com/" + row.Field<string>("path");

                html.Append("<li> <u>" + "<a href=" + "'" + href + "'>" + name + "</a></u></li>");
            }
            html.Append("</ol>");
            html.Append("</div>");

            return html.ToString();
        }
        #endregion       

    }

1 个答案:

答案 0 :(得分:1)

由于您在服务器端ASP.NET环境中工作,因此您的表单标记应具有(runat =“server”)属性(Why does ASP.NET webforms need the Runat=“Server” attribute?),如错误消息中所述:

ASPX页面(不是浏览器中生成的HTML标记)来源:

<form action="..." runat="server">
SERVER-SIDE CONTROLS LIKE asp:TextBox are here...
</form>

<强>更新:

似乎页面上根本没有表单标记。添加表单容器标记并将所有控件移入其中(使用“添加新项”向导创建一个新的ASPX页面以检查其外观):

<%@ Page Title="Dealer Services Hub" Language="C#"  AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="Hub._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    ...
    </head>
    <body>
        <form runat="server">
            ...MOVE ALL YOUR CONTROLS SUCH AS (<div id="wrapper">, asp:HiddenField etc.) HERE...
            <asp:HiddenField ID="hidDealers" runat="server"/>
            <asp:HiddenField ID="hidSelectedDealer" runat="server"  />
            <asp:HiddenField ID="hidSessionDealer" runat="server"  />
        </form>
    </body>
</html>