Just trying to make a simple pass with Ajax. Values artID and v are giving the correct values. Get Ajax error every time.
Controller = Article
Method = SaveRating
Ajax code:
$.ajax({
type: "POST",
url: 'Url.Action("SaveRating","Article")',
data: {
articleID: artID,
rate: v
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
error: function () {
alert("fail");
}
});
});
Controller:
[HttpPost]
public static int SaveRating(int articleID, int rate)
{
....
}
Do this.
public class Rating
{
public int ArticleID { get; set; }
public int Rate { get; set; }
}
[HttpPost]
public static int SaveRating(Rating rate)
{
//
}
Client side post
<script>
$.ajax({
type: "POST",
url: "/Article/SaveRating",
data: JSON.stringify({ rate:
ArticleID: "1",
Rate: "4"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("success");
},
error: function() {
alert("fail");
}
});
</script>
Try following ajax call,
$.ajax({
type: "POST",
url: "/Article/SaveRating",
data: { articleID: '1', rate: '5' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
First convert data into json string by JSON.stringify then send that data.
var data = {
articleID: 1,
rate: 5
};
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: '/Article/SaveRating',
data:data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
error: function () {
alert("fail");
}
});
Your URL isn't correct, change it to '@Url.Action("SaveRating","Article")'
:
$.ajax({
type: "POST",
url: '@Url.Action("SaveRating","Article")',
data: JSON.stringify({
articleID: artID,
rate: v
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
error: function () {
alert("fail");
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.