我有一个控制器,我想通过AJAX向其发送两个项:一个复杂对象(我的整个视图模型)和一个整数(特定行的id )。这个项目是用VB .Net编写的,但是如果有人能用C#回答这个问题,那就太好了(我对这两种语言都很了解)。任何一种语言都可以工作。
我可以将视图模型发送到控制器,没有任何问题。一旦我尝试包含整数,控制器就不能再路由请求。我知道这可能是我如何格式化我发布的数据的问题,但我还不能弄清楚我需要做什么。
我的控制器操作如下所示:
<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;
}
});我如何发布我的视图模型和整数(在这个例子中硬编码为3)?
发布于 2013-06-10 22:54:59
斯科蒂的帖子让我走上了正确的道路。我很想把它标记为答案,但它有一个小问题。整数将正确发布,但视图模型开始在控制器中显示为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;
}
}); 发布于 2013-06-10 22:46:34
试试这个:
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;
}
}); https://stackoverflow.com/questions/17026500
复制相似问题