【问题标题】:Parsing JSON data via a POST request in JS and C#通过 JS 和 C# 中的 POST 请求解析 JSON 数据
【发布时间】:2014-02-28 10:11:53
【问题描述】:

我使用 C# 作为后端,并希望向我的 C# 后端发出 JSON 对象/字符串请求。

我有这样的 C# 代码(用于 GET 请求):

[WebMethod]
[ScriptMethod(UseHttpGet = true,
ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static string GetOptionsServiceHttpGet(string variableId)
{
    // Do database stuff

    string retval = Serialize stuff/function goes here

    return retval;
}

javascript前端代码是这样的:

function Variable_Proxy() { }

       Variable_Proxy.GetVarOptionsHttpGet =
       function (variableId, successCallback, failureCallback) {
           $.ajax({
               type: "GET",
               contentType: "application/json; charset=utf-8",
               url: "file.aspx/GetOptionsServiceHttpGet?varId=\"" + variableId + "\",
               success: function (data) { successCallback(data); },
               error: function (data) { failureCallback(data); }
           });
       }

如何在点击时发布帖子或其他任何内容以将我的 JSON 对象发送到我的后端?

【问题讨论】:

    标签: c# javascript jquery .net


    【解决方案1】:

    例如,如果您发布的数据是一个简单的员工对象,您可以按如下方式执行 AJAX POST:

    C# 后端:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    /// <summary>
    /// Summary description for TestWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class TestWebService : System.Web.Services.WebService {
    
        public TestWebService () {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        [WebMethod]
        public string GetPersonData(int id, Person objPerson) {
            return "You have submitted data with ID: " + id.ToString() + " Name: " + objPerson.Name + " and Email: " +  objPerson.Email;
        }
    
        [WebMethod]
        public Employee CreateEmployee(int id, Person objPerson) {
            Employee objEmployee = new Employee();
            objEmployee.ID = id;
            objEmployee.Name = objPerson.Name;
            objEmployee.Email = objPerson.Email;
            return objEmployee;
        }
    
        public class Person{
            public string Name {get;set;}
            public string Email {get;set;}
        }
    
        public class Employee : Person {
            public int ID { get; set; }
        }
    }
    

    jQuery 前端:

    $("#btnSubmit").click(function () {
       // create the json string
       var jsonData = JSON.stringify({
               'id': $("#txtID").val(),
                objPerson: {
                      'name': $("#txtName").val(),
                      'email': $("#txtEmail").val()
                }
       });
    
       $.ajax({
          type: "POST",
          url: "/TestWebService.asmx/CreateEmployee",
          data: jsonData,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          error: function (xhr, status, error) {
                 //alert the error if needed
                 $("#result").html("Sorry there is an error: "   xhr.responseText);
          },
          success: function (responseData) {
                 // show the response data from webservice. Note: the d represent the object property data passed by webservice. It can an object of properties or just single property
                 $("#result").html("The id is " + responseData.d.ID + " And Name is " + responseData.d.Name + " And Email is " + responseData.d.Email);
          }
       });
    });
    

    【讨论】:

    • 酷 C# 长什么样子(+1 寻求帮助)
    • 不用担心,如果您觉得它有帮助,您介意接受它作为答案吗?
    • 在 Visual Studio 中创建新的 Web 服务时,IDE 会自动在您的 TestWebService.cs 文件顶部添加以下行:[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 此属性表示您的 Web 服务遵循给定的标准。 WS-I 不允许重载。
    • 由于 web 服务需要唯一的命名空间,这样它们就不会混淆彼此的模式和其他任何东西,属性 WebService(Namespace = "tempuri.org/")] 可以强制实现这种完整性。 URL(域、子域、子子域等)是一个聪明的标识符,因为它“保证”是唯一的,并且在大多数情况下你已经有了一个。
    • 一般你不能在 webmethod 中使用Response.Redirect。但是您可以在 return 语句之前尝试Context.Response.StatusCode = 307; Context.Response.AddHeader("Location","toMyOutputPage.aspx");。阅读此thread 了解更多详情。
    【解决方案2】:
     try
       {
    
    
           List<DataObject> DataList = new List<DataObject>();
            ...................
    
           return new { Result = "OK", Records = DataList };
    
      }  catch (Exception ex)  {
    
               return new { Result = "ERROR", Message = ex.Message };
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2012-01-13
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      相关资源
      最近更新 更多