2016-06-03 2 views
1

ajax를 사용하여 뷰에서 컨트롤러로 값을 전달하고 싶습니다.ajax를 사용하여 컨트롤러에 값을 전달하십시오.

<button onclick="addCommentByAjax()" >Save</button> 

내 스크립트를

function addCommentByAjax() { 
    $.ajax({ 
     type: "POST", 
     url: '/Survey/DoDetailSurvey', 

     data: { 
      choiceId: "1" 
     } 


}); 
} 

컨트롤러 :

[HttpPost] 
    public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId) 
    { 
    // 
    } 

하지만 choiceId 항상 널 (null)

답변

0
function addCommentByAjax() { 
$.ajax({ 
    type: "POST", 
    url: '/Survey/DoDetailSurvey?choiceId=1' 
    } 
}); 
} 

또한 다음과 같이 전달할 수

는 경우이 같은 개체를 사용하면 데이터를 구성해야 ViewModel을 전달하려면

이상 매개 변수의 경우

function addCommentByAjax() { 
$.ajax({ 
    type: "POST", 
    url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun' 
    } 
}); 
} 
2

몇 가지 변경하십시오.

먼저 버튼에 ID 또는 클래스를 지정하십시오. 두 번째로 인라인 onclick 함수를 제거하고 ajax click 함수를 사용하십시오. 그런 다음 요청 유형을 Post로 지정하십시오.

$('#btnComment').click(function() {  
    var choiceId = $('#YourChoiceId').val(); 

    $.ajax({ 
     url: '/Survey/DoDetailSurvey', 
     data: { 'choiceId' : choiceId}, 
     type: "post", 
     cache: false, 
     success: function (response) { 
      //do something with response 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      alert('error occured'); 
     } 
    }); 
}); 

그런 다음 컨트롤러는 당신이 당신의 ViewModel을 채우는 방법을 모르겠어요이

[HttpPost] 
public ActionResult DoDetailSurvey(string choiceId) 
{ 
    // 
} 

과 같아야합니다, 그래서 의도적으로 그들을 제거하고 작업하는 예를 보여. SurveyViewModel의

var data = {}; 
data.Property1 = some val; 
data.Property2 = "some val"; 

$.post('/Survey/DoDetailSurvey', data); 

샘플 구조는 내가 가정 :

public class SurveyViewModel 
{ 
    public int Property1 { get; set; } 
    public string Property2 { get; set; } 
} 
+0

감사합니다! 나는 그것을 얻는다 – binhhtse

+0

나는 그것을 시험해 보았다. 그러나 그것은 여전히 ​​null이다, 경고 : 에러가 발생했다. – binhhtse

+0

는'JSON.Stringify'를 사용한다. –

1

컨트롤러에는 두 개의 매개 변수가 있으므로 두 매개 변수가 모두 클라이언트 측을 식별해야합니다. 또한 contentType을 지정해야합니다.

당신은 지금처럼 페이로드를 확산 :

function addCommentByAjax() { 
    var payload = { 
     model: { 
     // whatever properties you might have 
     }, 
     choiceId: 1 
    }; 

    $.ajax({ 
     type: "POST", 
     url: '/Survey/DoDetailSurvey', 
     contentType: 'application/json', 
     data: JSON.stringify(payLoad) 
    }); 
} 
+0

Tks all! 효과가있다. – binhhtse

관련 문제