[英]pass value to controller by using 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總是為空
改變一些事情。
首先為您的按鈕分配一個id或類。第二個刪除內聯onclick
函數並使用ajax click
函數。 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');
}
});
});
然后你的控制器應該是這樣的
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
我不知道你是如何填充你的viewmodel,所以我故意刪除它們並顯示一個工作示例。
如果你想傳遞viewmodel,你應該像這樣構建你的數據對象:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
SurveyViewModel的示例結構我假設:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
由於控制器中有兩個參數,因此您需要從客戶端識別它們。 此外,您應指定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)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
你也可以像這樣通過
或更多參數
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.