繁体   English   中英

通过JS和C#中的POST请求解析JSON数据

[英]Parsing JSON data via a POST request in JS and C#

我将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对象添加到点击后的后端?

例如,如果您要发布的数据是一个简单的雇员对象,则可以执行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);
      }
   });
});
 try
   {


       List<DataObject> DataList = new List<DataObject>();
        ...................

       return new { Result = "OK", Records = DataList };

  }  catch (Exception ex)  {

           return new { Result = "ERROR", Message = ex.Message };
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM