【问题标题】:C# Web service to javascript Deserializing JSON ObjectC# Web 服务到 javascript 反序列化 JSON 对象
【发布时间】:2014-08-10 12:48:31
【问题描述】:

我有一个网络应用程序。在里面我有一个 asmx 文件“MyWebServices.asmx”,其中我有一个将 json 对象发送到我的 WebForm2.aspx 的 Web 方法。我的问题是如何用 Javascript 捕获这个对象存储它并用 javascript 显示它。 我在 MyWebServices.asmx 上的代码:

public class apointment
    {
        public string Fname{ get; set; }
        public string Lname{ get; set; }
        public string customerid { get; set; }

    }

[WebMethod]
    public string myapointment()
    {

        apointment myapointment1= new apointment();
       myapointment1.customerid = "123POW";
        myapointment1.Fname = "John";
        myapointment1.Lname = "JohnsLname";
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(myapointment1);
        return sJSON;
    }

我在 .net 页面 Javascript 上的代码:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "services/MyWebServices.asmx/myapointment",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {



                // Insert the returned HTML into the <div>.
                var myrant = data.d;

                $('#RSSContent').html(data.d);
            }
        });
    });


</script>

问题在于这段代码我正在使用一个字符串:

{"Fname":"John","Lname":"JohnsLname","customerid":"123POW"}

如何将此字符串转换为对象类型约会?我问是因为之后我可以在 html 上正确显示,我想创建约会列表。

【问题讨论】:

  • myapointment 方法中返回apointment 对象不是字符串...
  • 声明它以便它返回apointment并用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]标记你的方法
  • 好的,我做到了。如何使用 javascript 访问它?
  • data in success: function (data){ 是你的对象...
  • 我已将代码更改为 $('#RSSContent').html(data.Fname);我什么都没拿

标签: c# javascript asp.net json web-services


【解决方案1】:

您是否考虑过将以下代码用于 Web 服务。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public apointment myapointment()
{
    apointment myapointment1 = new apointment();
    myapointment1.customerid = "123POW";
    myapointment1.Fname = "John";
    myapointment1.Lname = "JohnsLname";

    return myapointment1;
}

其次,根据这个问题的答案 (Calling ASMX Web Service from Javascript),您是否取消了 web 服务顶部的这一行的注释。

//[System.Web.Script.Services.ScriptService]

您最后是否尝试过使用 Fiddler (http://www.telerik.com/fiddler) 来调试您的 Web 服务以确定 Web 服务是否返回正确的输出?使用具有以下设置的 Composer 选项卡:

您应该会看到对 Web 服务的请求显示在页面的左侧列中。单击 RawTextView 选项卡,查看是否显示了您期望的 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多