2013-07-22 2 views
10

양식 제출을 Ajax 호출로 바꾸려고합니다. 액션에 formcollection이 필요하고 새 모델을 만들고 싶지 않습니다. 그래서 전체 양식 (양식 제출과 마찬가지로)을 전달해야하지만 아약스 호출을 통해 전달해야합니다. Json을 직렬화하고 사용하려고했지만 formcollection이 비어 있습니다. 이 내 액션 서명입니다 : Ajax 호출을 사용하여 formcollection을 전달하는 방법은 무엇입니까?

var form = $("#onlineform").serialize();    
      $.ajax({ 
       url: "/Register/CompleteRegisteration",     
       datatype: 'json', 
       data: JSON.stringify(form), 
       contentType: "application/json; charset=utf-8",     
       success: function (data) { 
        if (data.result == "Error") { 
         alert(data.message); 
        } 
       } 
      }); 

지금 어떻게 formcollection에 데이터를 전달할 수 있습니다

: 여기

public ActionResult CompleteRegisteration(FormCollection formCollection) 

내 제출 버튼 클릭은?

답변

29

키 - 값 쌍들의 수이고, JSON 표현은 부적절한 데이터 포맷이다. (자연 여기 필요하지,하지만 것) POST로 설정 요청

  1. 유형 대신
  2. 직렬화 된 형식 :

    var form = $("#onlineform").serialize(); 
    $.ajax({ 
        type: 'POST', 
        url: "/Register/CompleteRegisteration", 
        data: form, 
        dataType: 'json', 
        success: function (data) { 
         if (data.result == "Error") { 
          alert(data.message); 
         } 
        } 
    }); 
    

    주요 변경 사항 : 당신은 직렬화 된 형식 문자열을 사용한다 요청으로 JSON 문자열 데이터

  3. contentType 제거 - 더 이상 JSON을 보내지 않습니다.
+0

"POST"행 뒤에 ","을 입력해야합니다. – PAVITRA

+1

@PAVITRA, added, thanks – Andrei

5

보십시오 FormCollection 이후

$(<your form>).on('submit',function(){ 
    $.ajax({ 
     url: "/Register/CompleteRegisteration" + $(this).serialize(), 
     // place the serialized inputs in the ajax call     
     datatype: 'json', 
     contentType: "application/json; charset=utf-8",     
     success: function (data) { 
      if (data.result == "Error") { 
       alert(data.message); 
      } 
     } 
    }); 
}); 
+0

감사합니다. 제출 ajax 호출을 첨부하는 것이 핵심이었습니다! – Armen

1

누구나 FormCollection에 데이터를 추가하려는 경우 아래에서 시도 할 수 있습니다.

<script type="text/javascript"> 
function SubmitInfo() 
{ 
    var id = $("#txtid").val();  
    var formData = $('#yourformname').serializeObject(); 
    $.extend(formData, { 'User': id }); //Send Additional data 

    $.ajax({ 
     url: 'Controlle/GetUser', 
     cache: false, 
     type: 'POST', 
     dataType: 'json', 
     data: decodeURIComponent($.param(formData)), 
     success: function (data) { 
      $('#resultarea').html(data); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      alert("AJAX error: " + textStatus + ' : ' + errorThrown); 
     } 
    }); 
} 

$.fn.serializeObject = function() { 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 
     if (o[this.name] !== undefined) { 
      if (!o[this.name].push) { 
       o[this.name] = [o[this.name]]; 
      } 
      o[this.name].push(this.value || ''); 
     } else { 
      o[this.name] = this.value || ''; 
     } 
    }); 
    return o; 
}; 
<script/> 

액션 방법은

public ActionResult GetUser(FormCollection frm) 
    { 
    int UserId = Convert.ToInt32(frm["user"]); 
    // your code 
    return Json(data, JsonRequestBehavior.AllowGet); 
    } 

은 자세한 내용은 링크를 참조하십시오. http://geekswithblogs.net/rgupta/archive/2014/06/25/combining-jquery-form-serialize-and-json.stringify-when-doing-ajax-post.aspx

+0

스택 사용자가 제안한대로 게시물 및 코드 및 설명을 추가했습니다. –

관련 문제