Getting "The resource cannot be found." when I use HttpPost attribute on an action-method that a jQuery ajax-post points to
II'm developing an ajax comment form in my .Net MVC project.
So far, I get a "The resource cannot be found" error,
UNLESS I remove the HttpPost attribute from the action method -- then it works.But for clear reasons, I want the post filter ... so what am I doing wrong??
Here's the form (labels and other irrelevant markup removed):
<form action="/SubmitComment">
<input class="commentFormCommenter" id="Commenter" name="Commenter" type="text" value="" />
<input class="commentFormEmail" id="Email" name="Email" type="text" value="" />
<textarea class="commentFormBody" cols="20" id="Body" name="Body" rows="2"></textarea>
<input id="PublicationId" name="PublicationId" type="hidden" value="3862" />
<input type="submit" value="submit" class="submit" />
</form>
...and I want to hi-jax it with jQuery like this:
$('form[action$="comment"]').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: 'post',
data: $(this).serialize(),
success: function (data) {
$('.tester').text('successful round-trip.');
}
});
});
...to an ActionMethod in my MVC project:
public class CommentController : Controller
{
[HttpPost]
public ActionResult SubmitComment(string Commenter, string Email, string Body, int Pu开发者_StackOverflow中文版blicationId)
{
return new EmptyResult();
// AT THIS POINT, SUCCESS IS AN EMPTY PAGE
}
}
... the route is mapped simply:
routes.MapRoute(
"",
"SubmitComment",
new { controller = "Comment", action = "SubmitComment" }
);
I just needed to add
method="Post"
to the form.
Try simplifying your code:
$('form[action$="comment"]').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$('.tester').text('successful round-trip.');
}
});
});
Instead of HttpPost
try with [AcceptVerbs(HttpVerbs.Post)]
.
精彩评论