c# – 使用jQuery AJAX将多个变量POST到ASP .NET MVC控制器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用jQuery AJAX将多个变量POST到ASP .NET MVC控制器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2458字,纯文字阅读大概需要4分钟。
内容图文
我有一个控制器,我想通过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;
}
});
内容总结
以上是互联网集市为您收集整理的c# – 使用jQuery AJAX将多个变量POST到ASP .NET MVC控制器全部内容,希望文章能够帮你解决c# – 使用jQuery AJAX将多个变量POST到ASP .NET MVC控制器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。