jquery post is it ajaxrequest?
i been trying to get this to work for solid 3 hours. im doing a jquery post but some where in the line im doing something wrong but i dont get what.
in my method i check if its a ajaxrequest and if it is i return a string message based on the outcome.
[HttpPost]
public ActionResult PostJquery(ContactViewModel viewModel)
{
if (Request.IsAjaxRequest())
{
if (!string.IsNullOrEmpty(viewModel.Email))
{
return Content("success");
}
else
{
return Content("Fail");
}
}
else
{
return RedirectToAction("About");
}
}
my jquery and html looks like this.
<% using (Html.BeginForm())
{%>
<%: Html.TextBoxFor(model => model.Email) %>
<br />
<br />
<%: Html.TextBoxFor(model => model.Title) %><br />
<input type="submit" value="Save" id="button" />
<%} %>
<script src="<%= Url.Content("~/Scripts/jquery-1.5.2.开发者_如何学Cjs") %>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#button').click(function (e) {
$.post('/Home/PostJquery', { viewModel: $('form').serialize() }, function (data) { alert(data); });
});
});
</script>
what it does is go into the method and redirect to the site about because its not a ajaxrequest, if i remove it it returns success but it takes me to a blank page with the text success writen. it dont trigger success in alert. what im i possibly doing wrong? should i use .post or .ajax?
thanks for input folks
You need to cancel the default action of the button which is to submit the form by returning false:
$(function () {
$('#button').click(function() {
$.post('/Home/PostJquery', $('form').serialize(), function (data) {
alert(data);
});
return false;
});
});
Also notice the way parameters are passed. The .serialize()
method already prepares the request so that's what you should send as second argument.
but a better way to AJAXify a form is to subscribe for the .submit()
event of this form:
$(function () {
$('form').submit(function() {
$.post(this.action, $(this).serialize(), function (data) {
alert(data);
});
return false;
});
});
And even better way is to use the jquery form plugin which turns your code into:
$(function () {
$('form').ajaxForm(function(data) {
alert(data);
});
});
Remark: make sure you set the proper content type on your server when returning from an AJAX request.
精彩评论