Reputation: 575
I'm getting a "bad request" error when I try to HTTP post to the "Home" controller using the following JQuery/AJAX. Does anyone see the cause?
This is pretty much a copy of the example obtained from here, except greatly simplified: JQUERY ajax passing value from MVC View to Controller. It seems it's not finding the controller, which confuses me -- I've fiddled with this a lot, and with no success.
Button in the view that throws a "bad request" error, and does not reach the controller:
<td> <input type="submit" class="btn-default" name="submit" value="Start Simulating-Jquery" id="btnSaveComments" />
<script> $('#btnSaveComments').click(function () {
$.ajax({
url: '<%:Url.Action("SaveComments")%>',
type: "post",
cache: false,
success: function (savingStatus) {
alert("save")
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.toString())
alert(ajaxOptions.toString())
alert(thrownError.toString())
}
});
});
</script>
</td>
Example of a button in the view that does work:
@Ajax.ActionLink("ActonLinkTest", "SaveComments", "Home",
new AjaxOptions
{
HttpMethod = "POST"
}
)
Controller (Home):
[HttpPost]
public ActionResult SaveComments()
{
return new EmptyResult();
}
EDIT: This also fails.
View:
<td>
<input type="submit" class="btn-default" name="submit" value="Start Simulating-Jquery #2" id="btnSaveComments2" />
<script>
$('#btnSaveComments2').click(function () {
var comments = 'a';
var selectedId = '1';
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id': selectedId, 'comments': comments },
type: "post",
cache: false,
success: function (savingStatus) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert('failed')//$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
</script>
</td>
Replacing the previous savecomments function with this one in the controller:
[HttpPost]
public ActionResult SaveComments(int id, string comments)
{
return new EmptyResult();
}
Upvotes: 1
Views: 1131
Reputation: 2898
Try Like this
var id = 1;
var comments = 'abc';
$.ajax({
data: { 'id': id, 'comments': comments },
url: '/Home/SaveComments1',
cache: false,
success: function (savingStatus) {
alert("save")
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.toString())
alert(ajaxOptions.toString())
alert(thrownError.toString())
}
});
});
Upvotes: 1
Reputation: 2460
Please try:
url: '<%= Url.Action("SaveComments") %>',
I think you have the wrong inline tag.
Upvotes: 0