1

I am working on asp.net application in which I want to add Products. Here is my design

<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>

Here is my code:-

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);
        }

    }

Here is 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();
    }

When I select any item from ddlCategory then the ddlSubCategory is binded according to selected value of ddlCategory. The Binding of ddlSubCategory is done on change event of ddlCategory using Jquery. The binding is working properly but When I click on the button the selectedvalue of ddlSubCategory is always comes null in Code behind window.

2
  • Reduce your code examples down to the relevant parts only please. Commented Oct 6, 2015 at 10:21
  • You won't be able to access the dropdown created at client side directly. Check the last section of this Article - aspsnippets.com/Articles/… Commented Oct 6, 2015 at 10:32

2 Answers 2

1

I think the reason ddlSubCategory is null on Postback is because your options are built client-side and are not part of the viewstate. A good trick is to add a hidden field to your html:

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

Then add this script inside your script block (before your function BindSubCategory):

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

When you click btnSave, you should have the value of the selected ddlSubcategory available on the server side by referencing hidSubcategoryValue.Value.

Sign up to request clarification or add additional context in comments.

Comments

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

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


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

1 Comment

Actually i want to get the selected value i code behind window not using jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.