How to call the controller method after clicking the checkbox?

Is it possible to make CheckBox call the controller method on click in the same way as ActionLink does? Basically, I want to replace this ActionLink :

 @Html.ActionLink("Switch status", "SwitchTaskIsComplete", "Task", new { taskId = task.TaskId, isComplete = !task.IsComplete, userId = Model.UserId }, null) 

with @Html.CheckBox which calls the same method

 SwitchTasksIsComplete(int taskId, bool isComplete, int userId) 

of TaskController and uses its checked property as the isComplete parameter each time it is clicked.

+4
source share
1 answer

You can use HTML onclick for this:

 @Html.CheckBox("mycheckbox", new { onclick="triggerLink()" }) 

Use @Url.Action instead of @Html.ActionLink to get only the URL:

 <script> function triggerLink() { var theUrl = '@Url.Action("SwitchTaskIsComplete", "Task", new {taskId = task.TaskId, isComplete = !task.IsComplete, userId = Model.UserId}, null)'; window.location = theUrl; } </script> 

You can also put the entire inline expression in the attribute:

 @{ var url = Url.Action("SwitchTaskIsComplete", "Task", new {taskId = task.TaskId, isComplete = !task.IsComplete, userId = Model.UserId}, null); } @Html.CheckBox("mycheckbox", new { onclick="window.location = '" + url + "'" }) 
+5
source

Source: https://habr.com/ru/post/1434310/