2016-06-03 17 views
1

Ich möchte den Wert von Sicht zu Controller mit Ajax übergeben.Wert an den Controller mit Ajax übergeben

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

Mein Skript:

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

     data: { 
      choiceId: "1" 
     } 


}); 
} 

Controller:

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

aber choiceId immer null

Antwort

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

Sie können auch so passieren

oder für weitere Parameter

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

Einige Dinge ändern.

Zuerst zuweisen Sie eine ID oder Klasse zu Ihrem Button.Second entfernen Inline onclick Funktion und verwenden Sie Ajax click function.Then geben Sie den Anfragetyp als 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'); 
     } 
    }); 
}); 

Dann Ihren Controller wie diese

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

aussehen soll, weiß ich nicht, wie Sie Ihre Viewmodel bevölkern, so dass ich entfernt sie absichtlich und ein funktionierendes Beispiel gezeigt.

Falls Sie passieren Viewmodel Sie Ihre Daten Objekt wie dieses Konstrukt sollte:

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

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

Probenstruktur SurveyViewModel Ich gehe davon aus:

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

Dank! Ich bekomme es – binhhtse

+0

Ich habe versucht, aber es immer noch null, alert: Fehler aufgetreten – binhhtse

+0

verwenden 'JSON.Stringify' –

1

Da zwei Parameter in Ihrem Controller vorhanden sind, müssen Sie sie beide auf der Clientseite identifizieren. Außerdem sollten Sie die contentType angeben.

Sie verteilt die Nutzlast wie so:

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 alle! es funktionierte – binhhtse

Verwandte Themen