これが私の見解です
<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 コントローラーのメソッドは次のとおりです。
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 に置き換えてみましたが、同じ結果になりました。