我有一个 Controller ,我想通过 AJAX 向其发送 2 个项目:一个复杂对象(我的整个 View 模型)和一个整数(特定行的 ID)。这个特定的项目是在 VB .Net 中,但如果有人能用 C# 回答这个问题,那就太好了(我对这两种语言都非常了解)。任何一种语言都可以。
我可以毫无问题地将 View 模型发布到 Controller 。一旦我尝试包含整数, Controller 就无法再路由请求。我知道这可能是我如何格式化我发布的数据的问题,但我一直无法弄清楚我需要做什么。
我的 Controller Action 看起来像:
<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;
}
});
如何发布我的 View 模型和整数(在此示例中硬编码为 3)?
最佳答案
Scottie 的帖子让我走上了正轨。我很想将其标记为答案,但它有一个小问题。整数会正确发布,但 View 模型开始在 Controller 中显示为 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;
}
});
关于c# - 使用 jQuery AJAX 将多个变量发布到 ASP .NET MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026500/