这是我的观点
<div>
@using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
{
@Html.TextBoxFor(x=> x.Name)<br />
@Html.TextBoxFor(x => x.LastName)<br />
@Html.TextBoxFor(x => x.Age)
<input type=submit value="submit" />
}
</div>
<script>
$(document).ready(function () {
$('#FormPost').submit(function (e) {
//This line will prevent the form from submitting
e.preventDefault();
alert('ajax post here');
$.ajax({
type: 'POST',
url: $('FormPost').attr('action'),
data: $('FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.statusText);
},
success: function (response) {
alert('resp: ' + response.data);
}
});
});
});
</script>
这些是 Home Controller 的方法:
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
return Json("name posted was: " + _vm.Name);
}
这是路线图
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
当页面加载时,它会转到 Index 操作方法,这是可以理解的。但是,当我提交表单时,它会再次转到 Index 操作方法。这是为什么?
显示警报消息“ajax post here”,然后显示成功警报(“resp:”+ response.data)。但是,由于我没有在索引中返回任何内容,因此我在警报框中收到 resp: undefined 。
如何修复此问题,以便表单发布转到 public JsonResult jQueryPost(IndexVM vm)
方法?我还尝试将 JsonResult 替换为 ActionResult,效果相同。
最佳答案
您忘记了 jQuery 选择器中的#
:
$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.statusText);
},
success: function (response) {
alert('resp: ' + response.data);
}
});
关于asp.net - jquery ajax post 转到 MVC 4 中的错误操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17325892/