arrgh
arrgh

Reputation: 667

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.

Upvotes: 5

Views: 8942

Answers (2)

Dwight
Dwight

Reputation: 730

@{
    var url = Url.Action("action", "controller");
}
<label class="some-style">
   <input type="checkbox" onclick="window.location='@url'" />
   <span class="Some-other-style">Your Label</span>
</label>

This solution implements a regular html checkbox expression with a url action, whenever the textbox is clicked, the action is submitted to the controller. You can also include a value in the case you need to know the checkbox's state.

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102793

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 + "'" })

Upvotes: 9

Related Questions