The jQuery posting event is
<script>
$(document).ready(function () {
$("#going").click(function () {
$.post("/Home/ToggleGoing",
{
going: $("#going").val()
},
function (data) {
//No success code.
});
});
});
</script>
And the action in control is
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ToggleGoing(bool going, int? id)
{
var e = db.Events.FindAsync(id);
However, the javascript console shows it got 500 error?
POST https://localhost:44300/Home/ToggleGoing 500 (Internal Server Error)
This: ValidateAntiForgeryToken
.
When you use $.post()
the hidden field that contains the validation token is not being included. You need to include it in your POST data:
$.post("/Home/ToggleGoing",
{
going: $("#going").val(),
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
}, function (data) {
});
Of course, this assumes that you've added a @Html.AntiForgeryToken()
to your form somewhere.
Correct your Post url :
$.post("/Home/ToggleGoing", { going: $("#going").val() , id:???//pass value of id }, function (data) {})
Make sure going
is of type bool
.
EDIT :-
as my suggestion in comments section worked for the questioner so im adding that also in answer.
Just remove [ValidateAntiForgeryToken]
token from Post controller or include ValidateAntiForgeryToken
as a parameter in $.Post()
.
I have answered the almost similar question at:
How to get {ID} in url “controller/action/id” in a post action?
As discribed in the above answer, you are also missing the id in the end of url as it is mapped like "{controller}/{action}/{id}" in RouteConfig.cs file in RegisterRoutes method. So your corrected Url will be:
"/Home/ToggleGoing/{id}" //in your case: "/Home/ToggleGoing/4"
Next is "going" is bool parameter. and to find the check box is checked or not "val()" is not the correct method, you should use it as:
$("#going").is(':checked')
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.