2012-11-16 1 views
1

JavaScript 처리기에 JavaScript 개체를 전달하고 값을 구문 분석하려면 어떻게해야합니까?자바 스크립트 개체가 ASP.NET 처리기로 전달

나는 같은 복잡한 유형의 객체 만들었습니다

function AccountObjCreate() { 
var AccountsView = {}; 
AccountsView.Username = null; 
AccountsView.Email = null; 
AccountsView.Password = null; 

return AccountsView; 
} 

을 그리고 채우 객체와 같은 그런 다음

var aView = AccountObjCreate(); 
aView.Username = $('#tbUserName').val().trim(); 
aView.Email = $('#tbEmail').val().trim().toLowerCase(); 
aView.Password = $('#tbPassword').val().trim(); 

내가 부르고 :

$.post("/Handlers/AccountHandler.ashx", { obj: aView }, 
     function (results) { 
      if (results.isSuccess) { 
       alert(results.msg); 
      } else { 
       alert(results.msg); 
      } 
     }, "json"); 

나는 그것을 볼 때 콘솔 내 모든 데이터를 aView json 내에서 볼 수 있습니다.

내 ASP.NET 처리기 페이지

context.Response.ContentType = "application/json"; 
context.Response.ContentEncoding = Encoding.UTF8; 
string obj = context.Request["obj"]; 

하지만 OBJ은 NULL입니다. 당신이 문자열로 직렬화한다 서버를 통해 객체를 얻기 위하여

답변

5

(당신이 방법을 사용할 수는 here 설명 또는 자바 스크립트 here에 대한 JSON 라이브러리 포함) 다음과 .NET JavaScriptSerializer 클래스를 사용하여 직렬화합니다.

JS 코드

var data = { 
    obj: JSON.stringify(aView) 
}; 
$.post("/Handlers/AccountHandler.ashx", data, function(results) { 
    if (results.isSuccess) { 
     alert(results.msg); 
    } else { 
     alert(results.msg); 
    } 
}, "json");​ 

그런 다음 서버 핸들러에 당신은 언급 JavaScriptSerializer 클래스와 JSON 문자열을 구문 분석 할 수 있습니다.

public class AccountsView { 
    public string Username; 
    public string Email; 
    public string Password; 
} 

public void ProcessRequest(HttpContext context) 
{ 
    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    string value = context.Request["obj"]; 
    var aView = serializer.Deserialize(value, typeof(AccountsView)); 

    context.Response.ContentType = "application/json"; 
    context.Response.ContentEncoding = Encoding.UTF8; 
} 
3

jQuery는 자동으로 객체를 문자열로 변환하지 않습니다. 너 혼자해야 해.

에 다운로드 : https://github.com/douglascrockford/JSON-js

이 당신의 HTML에 스크립트 참조를 추가로 $.post 호출을 변경 :

$.post("/Handlers/AccountHandler.ashx", { obj: JSON.stringify(aView, null, 2) }... 

는 또한 ContentType이 올바르지 않습니다. 나는 그냥 기본값으로 남겨 둘 것이다. 이 방식으로 JSON 데이터를 제출하는 동안 ContentType 자체는 JSON이 아닙니다. 콘텐츠 유형은 일반 게시물 데이터가 될 것입니다.

obj={"Username":"MyUsername", "Password":"MyPassword"... 

이 그것은 때때로 종류의 혼란을 얻을 수 JSON

{"obj":{"Username":"MyUsername", "Password":"MyPassword"... 

입니다 :이 포스트 데이터입니다.

더 나은 방법은 ASP.Net MVC를 살펴 보는 것입니다.

$.post("/Handlers/AccountHandler.ashx", JSON.stringify({ view: aView }, null, 2) }... 

는 쓰기 : 컨트롤러 방법은 클라이언트 측 코드에서이 작업을 수행 할 수 있도록 자동으로 닷넷 모델로 JSON 객체를 역 직렬화 할 수 있습니다.aView의 구조와 일치 순 클래스 :

class Account { 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string Email { get; set; } 
} 

그리고 그렇게 같은 컨트롤러 방법을 정의

public JsonResult SaveAccount(Account view) 

많이 간단한 일을 만듭니다. :)

+0

더 간단하지만 .NET 2.0에서만 실행되는 열악한 프로젝트의 경우 juan.facorro의 솔루션이 필요합니다. – SwissCoder