使用Web服务序列化json响应

时间:2013-05-01 09:15:12

标签: asp.net json web-services drop-down-menu knockout.js

由于我是淘汰赛,网络服务和所有这些事情的新手,我正在尝试使用淘汰赛和网络服务来填充下拉列表。

Html代码是

<body>
    <select data-bind="options: printers"></select>
</body>

并且javascript块是

<script>
    $(document).ready(function () {
        var viewModel = {
            printer: ko.observable(),
            printers: ko.observableArray()
        }
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "PapersDDLs.asmx/getPrinters1",
            data: "{}",
            dataType: "json",
            success: function (response) {
                viewModel.printers(response.d);
            }
        });

        ko.applyBindings(viewModel);
    });
</script>

我打电话的网络服务是

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Web.Script.Serialization

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

    <WebMethod()> _
    Public Function getPrinters1() As String
       Dim db As New DataClassesDataContext
       Dim printers = From p In db.Printers Select p
       Dim values As New List(Of PrinterItem)
       For Each pr In printers
          values.Add(New PrinterItem(pr.BrandModelName, pr.Id.ToString()))
       Next
      db.Dispose()
      Return New JavaScriptSerializer().Serialize(values)
   End Function

   End Class

问题是返回的字符串是逐个字符的。

任何帮助都是有价值的

谢谢!

1 个答案:

答案 0 :(得分:0)

您的网络服务中的功能略有不正确。您不需要自己进行Javascript序列化。因为您已将Web服务标记为System.Web.Script.Services.ScriptService,所以响应的内容将自动序列化为JSON。

方法签名应为:

Public Function getPrinters1() As List(Of PrinterItem)

并且return语句应为:

Return values