0

This question has been asked and answered many times, but I can't get it to work. My question look like this one, and this one and a third example.

What I would like to do is fill a option box from JSON object like in this and this questions. They are all slightly different, but similar, but I can't get it to work. Here's my code from the webservice:

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function HelloWorld(ByVal p_productCategoryId As Integer) As String
    Dim productCategory = ProductService.GetProductCategory(p_productCategoryId)

    'Dim productList = ProductService.GetProducts(productCategory)
    Dim productList = New List(Of Product)
    For cnt = 1 To 3
        Dim product = New Product(cnt)
        product.Productname = cnt.ToString & "|" & cnt.ToString
        productList.Add(product)
    Next

    Return productList.ToJSON

End Function

End Class

 <System.Runtime.CompilerServices.Extension()> _
Public Function ToJSON(Of T)(p_items As List(Of T)) As String
    Dim jSearializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
    Return jSearializer.Serialize(p_items)
End Function

If I use the following code:

function Test() {
  $.ajax({
     type: "POST",
     url: "Service.asmx/HelloWorld",
     data: "{'p_productCategoryId' : 1 }",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success:function(msg){
        alert(msg.d)
        },
     error: function() {
      alert("An error has occurred during processing your request.");
                        }
  });

};

I get this result:

[{"Id":1,"IsActive":false,"Category":null,"Productname":"1|1","Price":0},
{"Id":2,"IsActive":false,"Category":null,"Productname":"2|2","Price":0},
{"Id":3,"IsActive":false,"Category":null,"Productname":"3|3","Price":0}]

Which seems OK.

If I remove the 'd' from msg. The result in the alert is:

[object Object]

The 'work-in-progress' code to fill the option box is this (at the moment :):

function Test() {
$.ajax({
    type: "POST",
    url: "Service.asmx/HelloWorld",
    data: "{'p_productCategoryId' : 1 }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        $("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select"));
        $.each(msg.d, function () {
                           $("#prd_id").append($("<option></option>").val(this['Id']).html(this['Productname']));
        });
    },
    error: function () {
        alert("An error has occurred during processing your request.");
    }
});

};

I have tried several ways to get it to work taken from the examples I mentioned before, to no avail. Using msg.d fills to option box with the nummer of characters in the string. I tried to explicitly create a JSON object from the 'msg' with 'getJSON'. (Isn't that wat the 'datatype' is for?) I can't use named objects because I don't have that as you can see in the sample data. What am I missing?

Some how I can't get the code to see the array has three entries.

Community
  • 1
  • 1
Sigur
  • 317
  • 1
  • 3
  • 12

3 Answers3

1

I would probably use the Option constructor rather than HTML.

Assuming msg.d is really the array (that .d property is an ASP.Net thing):

success: function (msg) {
    var options = $("#prd_id")[0].options;
    options.length = 0;
    options.add(new Option("Please select", "[-]"));
    $.each(msg.d, function () {
        options.add(new Option(this.Productname, this.Id));
    });
},

Live Example | Source

The Option constructor takes the text as the first argument and the value as the second. The options list on a select element is a bit like an array, except that for compatibility with older browsers, instead of push you use add (or assign to options[options.length], either works).

Or if msg is the array (no .d), just remove .d:

success: function (msg) {
    var options = $("#prd_id")[0].options;
    options.length = 0;
    options.add(new Option("Please select", "[-]"));
    $.each(msg, function () {
        options.add(new Option(this.Productname, this.Id));
    });
},

Live Example | Source

If your response isn't being sent back with the correct MIME type, msg may actually be text, not an array. If so, you want to fix that on the server by returning the correct MIME type (application/json), although you can parse it manually:

msg = $.parseJSON(msg);

...and then use the above. Or of course, if it's coming back as msg.d (although that seems really unlikely):

msg.d = $.parseJSON(msg.d):
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • From your live example I can see that 'd' is a named object. Which is not present in my message from the webservice. That explains why it didn't work. Any way in your example you use 'd', so that doesn't work. Really cool that you created a live example so fast though. – Sigur Oct 28 '13 at 10:52
  • @Sigur: You said you alerted `msg.d` and got that, so I assumed `msg.d` was the array (that's something ASP.Net does, I've never understood why). If `msg` is the array, just remove the `.d`. – T.J. Crowder Oct 28 '13 at 10:53
  • @Sigur: I've added two further notes above. – T.J. Crowder Oct 28 '13 at 10:57
  • @TJ Crowder. Removing the 'd' was exactly my idea. So I did that already. Now the option box has two lines: one 'Please select' and the other named 'undefined'. Using the code from Palash below I get a lot of 'undefined' options to select. Do you think the webservice answer is not recognized correctly? – Sigur Oct 28 '13 at 11:02
  • @Sigur: It sounds like it. Use the debugger built into your browser, set a breakpoint on the first line with the `success` callback, and use the variable inspector to look at `msg`. All modern browsers have debuggers built into them, there's no reason to wander in the dark. :-) Look on the menus for "Dev Tools" or, on most browsers, just press F12. – T.J. Crowder Oct 28 '13 at 11:03
  • @TJ Crowder I will investigate this. I now have something to look for. Knowing what the jQuery code should be. Thanks – Sigur Oct 28 '13 at 11:13
  • @TJ Crowder This did the trick: `var data = $.parseJSON(msg.d);` Thanks – Sigur Oct 31 '13 at 11:19
0

You can do this:

$.each(msg.d, function (key, value) {
    $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname));
});

Fiddle Demo

palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

I tried to replicate according to your issue with my REST WCF which returns the Same JSON Data, and below sample worked,

<script type="text/javascript">
$(document).ready(function() {
});
var GetRawList = function() {
    $.ajax({
        type: "GET",
        url: "RestService/HelloWorld",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function(data) {
  //Change this "data.d" According to your returned JSON output header. 
            var result = data.d;  
   $("#prd_id").empty().append($("<option></option>").val("[-]").html("Please select"));
            $.each(result, function(key, value) {
            $("#prd_id").append($("<option/>").val(value.Id).html(value.Productname));
            });
        },
        error: function(xhr) {
            alert(xhr.responseText);
        }
    });
}

Akhil
  • 1
  • I have tried your code. The result is something I have seen before: a very long option list with no text. If I remove the 'd', there is one list option with no tekst. After the comments from TJ Crowder I have investigated a bit. I'm using a custom framework from my new employer and my assignment is to learn it. The framework seems to do something with .asmx related things. To make this work I'm going to use a WCF service and see what happens. Thanks – Sigur Oct 28 '13 at 15:23