我正在开发要在其中添加产品的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在窗口后面的代码中始终为空。

最佳答案

我认为ddlSubCategory在Postback上为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的值。

关于javascript - 如何在asp.net中使用jQuery获取下拉列表选择的值绑定(bind)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32967373/

10-11 15:02