我正在开发一个 ASP.net MVC 2.0 应用程序。
我有一个表单,输入数据后,用户点击提交。
在这里,我不想进行整个回发,而我只想发出 ajax 请求以将表单数据发送到相应的 Controller 方法,并插入并将响应发送到同一页面。
因为,我使用的是 MVC 2.0,所以我不能使用 AJax.beginForm。我需要依赖 jquery Ajax 方法。
请帮助解决这个问题。
我正在使用强类型 View 。
请您参考如下方法:
您可以使用 JavaScript 的序列化方法直接发布您的数据。
在 View 中
@model ViewModel
@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "FormId" }))
{
<input type="button" value="Save" onclick="SaveDemo();" />
}
java脚本保存功能
function SaveDemo() {
$.ajax({
url: '',
type: 'POST',
cache: false,
data: jQuery("#FormId").serialize(),
success: function (result) {
// do accordingly as per your result
} }); }
和 Controller 保存方法会喜欢:
[HttpPost]
public ActionResult Save(ViewModel viewModel)
{
if (this.ModelState.IsValid)
{
// save to DB
}
return this.View(viewModel);
}
