Search code examples
jqueryjsonasp.net-mvcviewdata

mvc- jquery - json encode attribute search


I am working with MVC and JQuery and I have the following situation: I have a dropdown list auto populated with ViewData["product"] (data is passed to this viewdata from database in the controller), I also have a textbox called price, my goal is when the user select a product the price textbox should be filled with the corresponding product price, I have a viewdata["retailprice"], this is what I got so far

 $("#productname").change(function ()
                {
                    getprice();
                })
                function getprice()
                {
                    var productname = $("#productname").val();
                    var clienttype = $("#clienttype").val();


                    if (clienttype  == "Retail")
                    {
                        var x = {};
      for(x in JSON.parse('@Html.Raw(Json.Encode(ViewData["retailprice"]))'))
                        {
                            if(x == productname)
                            {
                                $("#productprice").val(x);
                                break;
                            }
                        }
                    }   
                }

the value of the json encode looks something like this

[{"Disabled":false,"Group":null,"Selected":false,"Text":"1.75","Value":"1"},{"Disabled":false,"Group":null,"Selected":false,"Text":"2.50","Value":"2"},{"Disabled":false,"Group":null,"Selected":false,"Text":"4.90","Value":"3"},{"Disabled":false,"Group":null,"Selected":false,"Text":"4.70","Value":"4"},{"Disabled":false,"Group":null,"Selected":false,"Text":"8.70","Value":"6"},{"Disabled":false,"Group":null,"Selected":false,"Text":"50.00","Value":"10"}]

productname variable contain the value property ex. "2"so basically I want to do something like this

if(x.value == productname)
                        {
                            $("#productprice").val(x.text);
                            break;
                        }

I know that not the right syntax but that's only for explanation. FYI with the above code when I change the productname dropdown list the product price text box change value to 1 or 2 or 3 or 4 only and honestly I dont know from where these values are coming from


Solution

  • Check the documentation of for.. in loop here. Change code to this:

    const data = JSON.parse('@Html.Raw(Json.Encode(ViewData["retailprice"]))');
    for(x in data)
    {
            if(data[x].Value == productname)
            {
                    $("#productprice").val(data[x].Text);
                    break;
            }
    }