如何在asp.net中使用jquery获得下拉列表选择值绑定

本文关键字:下拉列表 选择 绑定 jquery asp net | 更新日期: 2023-09-27 18:16:25

我正在asp.net应用程序中工作,我想在其中添加产品。这是我的设计

<script type="text/javascript" language="javascript">
    function BindSubCategory() {
        var SubCategory = document.getElementById('<%= ddlCategory.ClientID%>');
        //alert(City.value);
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Admin/Add_Products.aspx/BindDatatoSubCategory",
            data: "{'Category':'" + SubCategory.value + "'}",
            dataType: "json",
            async: true,
            success: OnBrandSuccess,
            error: OnBrandError,
            failure: function (Data) {
                alert('Fail');
            }
        });
        function OnBrandSuccess(data) {
            //            alert('Success');
            //            $.each(data.d, function (key, value) {
            //                $("#ddlSubCategory").append($("<option></option>").val(value.SubCatID).html(value.SubCategoryName));
            //            });
            var Dropdown = $('#<%=ddlSubcategory.ClientID %>');
            Dropdown.append(new Option("Select", 0));
            $.each(data.d, function (key, value) {
                Dropdown.append($("<option></option>").val(value.SubCatID).html(value.SubCategoryName));
            });
        }
        function OnBrandError(Data) {
            alert(Data.d);
        }
    }
</script>
<h2 runat="server" id="HTitle">
    Add Products</h2>
<div class="row">
    <div class="col-md-12">
        <div class="table-wrapper">
         <table class="table table-bordered table-hover">
                <tr>
                    <td>
                        Category
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCategory" runat="server" CssClass="form-control" onchange="javascript:BindSubCategory()">
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorg43" runat="server" ControlToValidate="ddlCategory"
                            Display="Dynamic" SetFocusOnError="true" InitialValue="0" ErrorMessage="Select Category"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        Subcategory
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlSubcategory" runat="server" DataValueField="SubCatID"  CssClass="form-control" onchange="javascript:Check()">
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator44" runat="server" ControlToValidate="ddlSubcategory"
                            Display="Dynamic" SetFocusOnError="true" ErrorMessage="Select Subsategory"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        Product Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtProductName" runat="server" CssClass="form-control">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtProductName"
                            Display="Dynamic" SetFocusOnError="true" ErrorMessage="Enter Product Name"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                    </td>
                    <td>
                    </td>
                </tr>
                <tr>
                    <td>
                        Cost
                    </td>
                    <td>
                        <asp:TextBox ID="txtCost" runat="server" CssClass="form-control">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtCost"
                            Display="Dynamic" SetFocusOnError="true" ErrorMessage="Enter Cost"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        Discount
                    </td>
                    <td>
                        <asp:TextBox ID="txtDiscount" runat="server" CssClass="form-control">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtDiscount"
                            Display="Dynamic" SetFocusOnError="true" ErrorMessage="Enter Discount"></asp:RequiredFieldValidator>
                    </td>
                </tr>
            </table>
            <table class="table table-bordered table-hover" style="margin-top: -2%">
                <tr>
                    <td>
                        Product Description
                    </td>
                    <td>
                        <CKEditor:CKEditorControl ID="CKEditor1" runat="server">
                        </CKEditor:CKEditorControl>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" SetFocusOnError="true"
                            ErrorMessage="Enter Product Description" ControlToValidate="CKEditor1" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                            <input type="button" name="Cancel" value="Cancel" id="Button2"  runat="server" onserverclick="btnSave_ServerClick"  class="btn-success btn" />
                    </td>
                </tr>
            </table>
            <asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
        </div>
    </div>
</div>
下面是我的代码:-
protected void btnSave_ServerClick(object sender, EventArgs e)
    {
        try
        {
            Products objProducts as New Products();
            objProducts.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue);
            objProducts.SubCategory = Convert.ToInt64(ddlSubcategory.SelectedValue);
            objProducts.ProductName = txtProductName.Text;
            objProducts.Description = Server.HtmlEncode(Regex.Replace(CKEditor1.Text, "(?i)</?div[^>]*>", ""));
            objProducts.Price = Convert.ToDecimal(txtCost.Text);
            objProducts.Discount = Convert.ToDecimal(txtDiscount.Text);
            if (Page.RouteData.Values["ID"] != null)
            {
                objProducts.ProductID = Convert.ToInt32(Page.RouteData.Values["ID"].ToString());
                objProducts.Flag = "U";
                objProducts.UpdatedBy = Session["Admin"].ToString();
                objProducts.AddedBy = "NA";
            }
            else
            {
                objProducts.UpdatedBy = "NA";
                dt = new Products().SelectDuplicate(objProducts.CategoryID, objProducts.SubCategory, objProducts.ProductName);
                if (dt.Rows.Count > 0)
                {
                    objProducts.Flag = "D";
                }
                else
                {
                    objProducts.Flag = "I";
                    objProducts.AddedBy = Session["Admin"].ToString();
                }
            }
            if (objProducts.Flag.Equals("D"))
            {
                lblMsg.Visible = true;
                lblMsg.Text = "This Products already exists. please enter another Product.";
            }
            else
            {
                retval = new Products().insert(objProducts);
                if (retval > 0)
                {
                    if (objProducts.Flag.Equals("I"))
                    {
                    }
                    lblMsg.Visible = true;
                    lblMsg.Text = "Successfully saved..";
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

这里是WebMethod:

[WebMethod]
    public static SubCategory[] BindDatatoSubCategory(string Category)
    {
        DataTable dt = new DataTable();
        List<SubCategory> details = new List<SubCategory>();
        dt = new SubCategory().SelectByCategory(Convert.ToInt32(Category));
        foreach (DataRow dtrow in dt.Rows)
        {
            SubCategory objSubCategory = new SubCategory();
            objSubCategory.SubCatID = Convert.ToInt64(dtrow["SubCatID"].ToString());
            objSubCategory.SubCategoryName = dtrow["SubCategory"].ToString();
            details.Add(objSubCategory);
        }
        return details.ToArray();
    }

当我从ddlCategory中选择任何项时,则根据ddlCategory的选定值绑定ddlSubCategoryddlSubCategory的绑定是使用Jquery在ddlCategory的变化事件上完成的。绑定工作正常,但当我点击按钮时,ddlSubCategory的selectedvalue总是在窗口后面的代码中出现null。

如何在asp.net中使用jquery获得下拉列表选择值绑定

我认为ddlSubCategory在Postback上为null的原因是因为您的选项是建立在客户端并且不是视图状态的一部分。一个好技巧是在html:

中添加一个隐藏字段。
<asp:HiddenField ID="hidSubcategoryValue" runat="server" />

然后将此脚本添加到脚本块中(在函数BindSubCategory之前):

$(document).ready(function() {
    $('#<%=ddlSubcategory.ClientID %>').change(function() {
        $('#<%=hidSubcategoryValue.ClientID %>').val(this.value);
    });
});

当您单击btnSave时,您应该通过引用hidSubcategoryValue.Value在服务器端获得所选ddlSubcategory的值。

var ddl = document.getElementById("<%=ddlCategory.ClientID%>");
var SelVal = ddl.options[ddl.selectedIndex].text;

alert(SelVal); //SelVal is the selected Value