JSON 개체를 ASP로 전송했습니다.NET WebMethod, jQuery 사용
저는 이 일을 3시간 동안 하고 포기했습니다.나는 단지 ASP에 데이터를 보내려고 합니다.JQuery를 사용하는 NET 웹 메서드입니다.데이터는 기본적으로 키/값 쌍의 집합입니다.그래서 저는 배열을 만들고 그 배열에 쌍을 추가하려고 했습니다.
내 웹 메서드(aspx.cs )는 다음과 같습니다(JavaScript에서 빌드하고 있는 것에 대해 잘못되었을 수도 있습니다, 저는 잘 모르겠습니다.
[WebMethod]
public static string SaveRecord(List<object> items)
{
...
}
다음은 제 샘플 JavaScript입니다.
var items = new Array;
var data1 = { compId: "1", formId: "531" };
var data2 = { compId: "2", formId: "77" };
var data3 = { compId: "3", formId: "99" };
var data4 = { status: "2", statusId: "8" };
var data5 = { name: "Value", value: "myValue" };
items[0] = data1;
items[1] = data2;
items[2] = data3;
items[3] = data4;
items[4] = data5;
JQuery AJAX 전화입니다.
var options = {
error: function(msg) {
alert(msg.d);
},
type: "POST",
url: "PackageList.aspx/SaveRecord",
data: { 'items': items },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
var results = response.d;
}
};
jQuery.ajax(options);
오류가 발생했습니다.
Invalid JSON primitive: items.
내가 이렇게 하면,
var DTO = { 'items': items };
데이터 매개 변수를 다음과 같이 설정합니다.
data: JSON.stringify(DTO)
그러면 다음 오류가 발생합니다.
Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027
이 예제에서는 데이터 매개 변수가 다음과 같은 경우에 작동합니다.
data: "{'items':" + JSON.stringify(items) + "}"
JSON 문자열을 ASP로 전송해야 합니다.NET AJAX.실제 JSON 개체를 jQuery의 데이터 매개 변수로 지정하면 &k=v?k=v 쌍으로 직렬화됩니다.
이미 읽은 것처럼 보이지만 jQuery, JSON.stringify 및 ASP에서 JavaScript DTO를 사용하는 예를 다시 한 번 살펴 보십시오.NET AJAX.이 작업에 필요한 모든 것을 포함합니다.
참고: "스크립트 서비스"에서 JSON을 수동으로 역직렬화하기 위해 JavaScriptSerializer를 사용해서는 안 됩니다(다른 사용자가 제안한 대로).지정된 유형의 매개 변수를 기반으로 메서드에 자동으로 이 작업을 수행합니다.만약 당신이 그것을 하고 있는 자신을 발견한다면, 당신은 그것을 잘못하고 있는 것입니다.
AJAX를 사용하는 경우.NET 저는 항상 입력 매개 변수를 단순한 오래된 개체로 만든 다음 자바스크립트 디시리얼라이저를 사용하여 원하는 유형으로 숨깁니다.적어도 그런 방식으로 디버그하고 웹 메서드가 수신하는 개체 유형을 확인할 수 있습니다.
jQuery를 사용할 때 개체를 문자열로 변환해야 합니다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/js/jquery.js" />
</Scripts>
</asp:ScriptManager>
<div></div>
</form>
</body>
</html>
<script type="text/javascript" language="javascript">
var items = [{ compId: "1", formId: "531" },
{ compId: "2", formId: "77" },
{ compId: "3", formId: "99" },
{ status: "2", statusId: "8" },
{ name: "Value", value: "myValue"}];
//Using Ajax.Net Method
PageMethods.SubmitItems(items,
function(response) { var results = response.d; },
function(msg) { alert(msg.d) },
null);
//using jQuery ajax Method
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "WebForm1.aspx/SubmitItems",
data: {"items":items.toString()}, // array to string fixes it *
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
jQuery.ajax(options);
</script>
그리고 비밀번호
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomEquip
{
[ScriptService]
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void SubmitItems(object items)
{
//break point here
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
}
}
}
다음은 우리 프로젝트의 코드 조각입니다. 개체를 문자열로 묶지 않고 날짜 값을 지정하는 데 어려움을 겪었습니다. 이것이 누군가에게 도움이 되기를 바랍니다.
// our JSON data has to be a STRING - need to send a JSON string to ASP.NET AJAX.
// if we specify an actual JSON object as jQuery's data parameter, it will serialize it as ?k=v&k=v pairs instead
// we must also wrap the object we are sending with the name of the parameter on the server side – in this case, "invoiceLine"
var jsonString = "{\"invoiceLine\":" + JSON.stringify(selectedInvoiceLine) + "}";
// reformat the Date values so they are deserialized properly by ASP.NET JSON Deserializer
jsonString = jsonString.replace(/\/Date\((-?[0-9]+)\)\//g, "\\/Date($1)\\/");
$.ajax({
type: "POST",
url: "InvoiceDetails.aspx/SaveInvoiceLineItem",
data: jsonString,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
서버 메서드 서명은 다음과 같습니다.
[WebMethod]
public static void SaveInvoiceLineItem(InvoiceLineBO invoiceLine)
{
[WebMethod]를 다른 속성으로 장식합니다.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
나는 이것이 시스템에 있다고 생각합니다.웹.서비스.스크립팅 중...
링크 http://www.andrewrowland.com/article/display/consume-dot-net-web-service-with-jquery 을 참조하십시오.
이것이 데이터를 정의하는 방법입니다(JSON).
data: { 'items': items },
그리고 이런 식으로 되어야 합니다.
data: '{ items: " '+items +' "}',
기본적으로 매개 변수를 직렬화하는 것입니다.
언급URL : https://stackoverflow.com/questions/1146110/sending-json-object-successfully-to-asp-net-webmethod-using-jquery
'source' 카테고리의 다른 글
마리아의 데이터를 업데이트하기 위해 WPF 클라이언트에 메시지를 보내기 위한 신호 RDB (0) | 2023.09.01 |
---|---|
내용 페이지에서 마스터 페이지 컨트롤에 액세스하는 방법 (0) | 2023.09.01 |
PHP 치명적 오류: 빈 속성에 액세스할 수 없습니다. (0) | 2023.09.01 |
안드로이드에서 원형 이미지 뷰를 만드는 방법은 무엇입니까? (0) | 2023.09.01 |
봄/Java 오류: JDK 1.5 이상에서 네임스페이스 요소 'annotation-config'... (0) | 2023.09.01 |