Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two tables Products and Categories .
I have a form with Product Price, Product Name and CategoryName dropDwon
When I try to Insert Data in the database , the CategoryName is saved as null.

This is Add method I have used to save the data in data base.
C#
<pre>function Add() {
    var res = validate();
    if (res == false) {
        return false;
    }
    var proObj = {
        ProductName: $('#ProductName').val(),
        ProductPrice: $('#ProductPrice').val(),
        
        CategoryName: $('#CategoryName option:selected').val()
         //CategoryName is saved as null in db
      
    };
    
    
    $.ajax({
        url: "/AjaxProducts/Add",
        data: JSON.stringify(proObj),
        type: "POST",
        contentType: "application/json;charset=utf-8",
        
        dataType: "json",
        success: function (result) {
            //$("#ddlcountry").append($("<option></option>").val
            //(value.CountryId).html(value.CountryName));
            loadData();
            $('#myModal').modal('hide');
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}


What I have tried:

DropDownList
C#
<pre><div>
                        @Html.DropDownList("CategoryName", new SelectList(string.Empty, "Value", "Text"), "Please select a category",  new { @style = "width:250px;" })
                    </div>
Posted
Updated 31-Jul-17 11:21am
Comments
Karthik_Mahalingam 1-Aug-17 4:15am    
run this in the console window and check what value you are getting
$('#CategoryName option:selected').val()

1 solution

You can get CategoryName value just using the id without option:selected selector, because the function val() return the selected value from the selected option.
CategoryName: $('#CategoryName').val()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900