In the cshtml file, I have the following javascript in Home/Details/4
. 4 is the ID.
<script>
$(document).ready(function () {
$("#checkbox").click(function () {
$.post(
"Home/Toggle",
{ checkbox: $("#checkbox").val() },
function (data) {
});
});
});
</script>
The following is the action code in the controller.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Toggle(bool checkbox)
{
...... // How to get ID?
var x = db.XXXX.Find(id);
How to get the ID? From some routing data, or Url, or let the front jQuery posting pass it?
Is it possible to get the ID from the action method without passing from the front html page?
First of all slash before the controller name in the url is missing:
"/Home/Toggle"
Next mistake is checkbox value can not be check by using val() method but it can be checked using:
$("#checkbox").is(':checked')
Next you have to append id after the url as it mapped like "controller/action/{id}" in RouteConfig.cs file in RegisterRoutes method.
So your final correct url will be:
"/Home/Toggle/{id}" //in your case: "/Home/Toggle/4"
In Action method "id" parameter is also missing. Corrected Action method is:
[HttpPost]
[ValidateAntiForgeryToken]
public void Toggle(bool checkbox, int id)
{
}
And your complete and corrected Jquery code is:
$.post("/Home/Toggle/4", { checkbox: $("#checkbox").is(':checked') }, function (data) {
});
In your script, assign the id
var id = '@Model.ID';
then include it when posting back
$.post("Home/Toggle", { checkbox: $("#checkbox").val(), ID: id }, function (data) { ...
and adjust your post method to
public ActionResult Toggle(int ID, bool checkbox)
{
....
It all depends what your html looks like? You probably want to save your id as a hidden or data-some-name
on to a html element.
@Html.HiddenFor(Model => Model.NameId)
or
<div class="some-class" data-id="@Model.NameId"></div>
Your action should take both parameters you want to pass in (or view model for that matter).
public ActionResult Toggle(bool checkbox, int id)
{
Your post should look like this. Note this is when using the hidden input "store" method.
$.post("Home/Toggle", { checkbox: $("#checkbox").val(), id: $('.NameId').val() }, function (data) {
});
If your url
is this Home/Details/4
then you can get 'id'
as :-
public ActionResult Toggle(bool checkbox, int? id) //<----get 'id' this way
{}
you need to change going to id in your ajax post function and add id to Toggle function or add new toggle function with id as parameter.
If you want to keep going value in post function you need to add a new routing