Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a controller method after a checkbox gets clicked?

Is it possible to make CheckBox invoke a controller method on click just like it does ActionLink? 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 a @Html.CheckBox, which invokes the same method

SwitchTasksIsComplete(int taskId, bool isComplete, int userId)

of TaskController and uses its checked property as isComplete parameter every time it gets clicked.

like image 390
arrgh Avatar asked Sep 14 '12 22:09

arrgh


1 Answers

You can use the HTML onclick for this:

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

Use @Url.Action instead of @Html.ActionLink to get just 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 could also put the whole expression inline 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 + "'" })
like image 169
McGarnagle Avatar answered Oct 18 '22 05:10

McGarnagle