[英]Using jQuery AJAX to POST multiple variables to an ASP .NET MVC Controller
我有一個控制器,我想通過AJAX發布2個項目:一個復雜的對象(我的整個viewmodel)和一個整數(特定行的id)。 這個特殊項目是在VB .Net中,但是如果有人能用C#回答這個問題,那就沒關系了(我對這兩種語言都很了解)。 這兩種語言都可行。
我可以將viewmodel POST到控制器沒有任何問題。 一旦我嘗試包含整數,控制器就不能再發送請求了。 我知道這可能是我如何格式化POST的數據的一個問題,但我無法確切地知道我需要做什么。
我的控制器動作如下:
<HttpPost>
Public Function UpdateFromDate(viewModel As RetirementBenefitEstimateViewModel, estimateId) As ActionResult
If viewModel IsNot Nothing AndAlso viewModel.Estimate IsNot Nothing AndAlso viewModel.Estimate.RetirementBenefitsEstimates IsNot Nothing Then
For Each item In viewModel.Estimate.RetirementBenefitsEstimates.Where(Function(est) est.EstimateId = estimateId)
' this is where I update the affected row
item.UpdateFromDate(viewModel.DateOfBirth, viewModel.EmploymentStartDate, viewModel.PersonId)
Next item
End If
' Get the previous ViewModel from session
PerformSessionAction(Of RetirementBenefitEstimateViewModel)(SessionConstants.RetirementEstimate, currentEstimate, SessionAction.GetVar)
' update it's .Estimate property
currentEstimate.Estimate = viewModel.Estimate
' save the updated ViewModel to session
PerformSessionAction(Of RetirementBenefitEstimateViewModel)(SessionConstants.RetirementEstimate, currentEstimate, SessionAction.SetVar)
' finished!
Return New HttpStatusCodeResult(HttpStatusCode.OK)
End Function
我視圖中的jquery AJAX調用如下所示:
$.ajax({
type: "POST",
url: '@Url.Action("UpdateFromDate")',
data: { viewModel : model, estimateId : 3 }
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (msg) {
//alert(JSON.stringify(msg));
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
如何發布我的viewmodel和整數(在本例中硬編碼為3)?
斯科蒂的帖子讓我走上正軌。 我很想把它標記為答案,但它有一個小問題。 整數將正確POST,但viewmodel在控制器中開始顯示為null。 修復此問題所需的只是一個簡單的JSON.parse調用。
我的AJAX調用最終看起來像:
var params = {
viewModel: JSON.parse(model),
estimateId: 3
};
$.ajax({
url: '@Url.Action("UpdateFromDate")',
type: "POST",
dataType: 'json',
data: JSON.stringify(params),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (msg) {
//alert(JSON.stringify(msg));
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
嘗試這個:
var params = {
viewModel: model,
estimateId: 3
};
$.ajax({
url: '@Url.Action("UpdateFromDate")',
type: "POST",
dataType: 'json',
data: JSON.stringify(params),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (msg) {
//alert(JSON.stringify(msg));
return true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.