如何在asp.net中使用jquery获取dropdownlist选择的值绑定?

时间:2015-10-06 10:14:44

标签: javascript c# jquery asp.net ajax

我正在研究我想要添加产品的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中选择任何项目时,ddlSubCategory会根据所选的ddlCategory值进行绑定。 ddlSubCategory的绑定是使用Jquery在ddlCategory的更改事件上完成的。绑定工作正常但当我单击按钮时,ddlSubCategory的selectedvalue在代码隐藏窗口中始终为空。

2 个答案:

答案 0 :(得分:1)

我认为在Postback上ddlSubCategory为null的原因是因为您的选项是在客户端构建的,并且不是viewstate的一部分。一个好方法是在你的html中添加一个隐藏字段:

<asp:HiddenField ID="hidSubcategoryValue" runat="server" />

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

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

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

答案 1 :(得分:0)

var ddl = document.getElementById("<%=ddlCategory.ClientID%>");

var SelVal = ddl.options[ddl.selectedIndex].text;


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