Here is my view
<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>
This is the Home controller's method the form posts to:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
return Json("name posted was: " + _vm.Name);
}
When I submit the form I get a 'resp: undefined' in the alert box. How do I return the text "name posted was: .... " back to the view on a successful post?
Also for exceptions when I added this line to the action
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
throw new Exception("custom error string from action");
return Json("name posted was: " + _vm.Name);
}
I get the message 'error: Internal Server error'. I want to return the text of the message in the error like so: 'error: custom error string from action' what is the way to do that?
Thanks