2012-01-20 7 views
3

웹 메서드 EmailFormRequestHandler에 아약스 게시를 만들고 있는데, 클라이언트 측에서 (방화 광구를 통해) 요청 상태가 200이지만 멈춤 지점에 도달하지 않았습니다 (첫 줄 webmethod의) 내 webmethod. json 매개 변수가 모두 object 이었지만 json을 deserialize하는 방식으로 모든 것을 문자열로 변경해야했습니다.json string을 webmethod에 매개 변수로 전달합니다.

JS :

function SubmitUserInformation($group) { 
    var data = ArrayPush($group); 
    $.ajax({ 
     type: "POST", 
     url: "http://www.example.com/components/handlers/FormRequestHandler.aspx/EmailFormRequestHandler", 
     data: JSON.stringify(data), // returns {"to":"[email protected]","from":"[email protected]","message":"sdfasdf"} 
     dataType: 'json', 
     cache: false, 
     success: function (msg) { 
      if (msg) { 
       $('emailForm-content').hide(); 
       $('emailForm-thankyou').show(); 
      } 
     }, 
     error: function (msg) { 
      form.data("validator").invalidate(msg); 
     } 
    }); 
} 

영문 : 당신은 당신이 중단 점을 설정하려는 의미

[WebMethod] 
public static bool EmailFormRequestHandler(string json) 
{ 
    var serializer = new JavaScriptSerializer(); //stop point set here 
    serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); 
    dynamic obj = serializer.Deserialize(json, typeof(object)); 

    try 
    { 
     MailMessage message = new MailMessage(
      new MailAddress(obj.to), 
      new MailAddress(obj.from) 
     ); 
     message.Subject = "email test"; 
     message.Body = "email test body" + obj.message; 
     message.IsBodyHtml = true; 
     new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(message); 
     return true; 
    } 
    catch (Exception e) 
    { 
     return false; 
    } 
} 
+0

그래서 당신이 말하는 상태 코드는'200'하지만, 오류도 성공 콜백도 실행되지 않습니까? – Rafay

+0

@ 3nigma correct – bflemi3

답변

7

당신은 jQuery를 JSON 포스트에 콘텐츠 형식을 놓치고 :

contentType: "application/json; charset=utf-8", 

은이 문서를 참조하십시오. 인터넷 아카이브에서

  • 나는 유사한 문제가있을 때 그것은 나를 크게 도움 EnablePageMethods에 대한 ScriptManager.

    또한, 당신은 당신의 WebMethod에 JSON 직렬화 객체를 직렬화 할 필요가 없습니다. ASP.NET이 그렇게하도록하십시오. 이 귀하의 WebMethod의 서명을 변경합니다 (I 단어에 "이메일"을 추가 눈치 "을"과 "에서"다음은 C#을 키워드는 그것이 키워드와 동일한 이름의 변수 나 매개 변수에 대한 나쁜 관행이기 때문에. 당신은 JSON.stringify()가 올바르게 문자열 직렬화 있도록 그에 따라 자바 스크립트를 변경해야합니다 : debuging은 프론트 엔드가 먼저 발생하면서

    public Dictionary<string, object> JsonToDictionary(dynamic request) 
    { 
    JObject x = JObject.FromObject(request); 
    Dictionary<string, object> result = new Dictionary<string, object>(); 
    
    foreach (JProperty prop in (JContainer)x) 
        { 
         result.Add(prop.Name, prop.Value); 
        } 
    
    return result; 
    } 
    

    내가 그것을 사용

    // Expected JSON: {"toEmail":"...","fromEmail":"...","message":"..."} 
    
    [WebMethod] 
    public static bool EmailFormRequestHandler(string toEmail, string fromEmail, string message) 
    { 
        // TODO: Kill this code... 
        // var serializer = new JavaScriptSerializer(); //stop point set here 
        // serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); 
        // dynamic obj = serializer.Deserialize(json, typeof(object)); 
    
        try 
        { 
         var mailMessage = new MailMessage(
          new MailAddress(toEmail), 
          new MailAddress(fromEmail) 
         ); 
         mailMessage.Subject = "email test"; 
         mailMessage.Body = String.Format("email test body {0}" + message); 
         mailMessage.IsBodyHtml = true; 
         new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(mailMessage); 
         return true; 
        } 
        catch (Exception e) 
        { 
         return false; 
        } 
    } 
    
  • +1

    에 설정되었습니다. (다만 알지 못했을 경우를 대비하여) JSON.stringify()는 IE7에서 작동하지 않습니다. [JSON2.js] (https://github.com/douglascrockford/JSON-js) –

    +0

    이 필요합니다. 실제로 이것이 내가 한 일입니다. 필드를 추가해야 할 때 실제로 유지 관리 할 수 ​​없으므로 이상적인 솔루션은 아닙니다. 그것은 통제에서 빨리 벗어날 수 있지만, 지금 당장 끝난 일입니다. 감사 마리오 !! – bflemi3

    +0

    당신을 진심으로 환영합니다. 나는 복잡한 물건을 전달하려고 시도하지 않았지만, 그것이 기회를 줄만한 가치가 있다고 생각합니다. –

    0

    ? 불그스레 한 점에 그 점을 설정하지 마십시오. VS 자체에 해당 중단 점을 설정하십시오. 그런 다음 VS를 로컬 IIS에 연결하십시오.

    그런데 아약스 호출에서 세 가지 매개 변수를 설정하면 웹 메소드가 하나만 사용됩니다. 매개 변수 이름은 동일해야합니다.

    ajax 호출에서 데이터 속성의 형식도 좋지 않습니다. 그것은이

    data: '{"to":"[email protected]","from":"[email protected]","message":"sdfasdf"}', 
    

    이 액자한다 ''과 같아야합니다

    +0

    정지 지점이 vs – bflemi3

    -1
    내가 눈치

    우선은 contentType이 누락 것입니다 : "응용 프로그램/JSON을, 캐릭터 세트 = UTF-8"을 $ 아약스에서 . 또한 $ .ajax에 전체 콜백을 추가하면 jqXHR, textStatus가 반환됩니다. 나는 완전한 콜백 textStatus 때문에 ("취소" "성공", "notmodified", "오류", "타임 아웃", 또는 "parsererror") 다음 중 하나를 도움이 될 것입니다 생각합니다. 문제를 추적하는 데 도움이 될 수 있습니다.

    0

    이 코드 될 수있다 누군가가 도움이 .

    관련 문제