mardi 9 mars 2021

How to add onclick function to HTML.CheckBoxFor in Asp.net mvc 5?

I have a checkbox, that should fire an onclick event, if the value of the checkbox was changed. The onclick event itself should activate a controller method, that is doing then something. The checkbox is bounded to a model. I saw a solution with javascript like this:

 @foreach (var item in Model)
 {
     @Html.CheckBoxFor(modelItem => item.IsM2oliePatient, new { onclick = 'myClickMethod'});
 }
<script>
    function myClickMethod() {
        var theUrl = '@Url.Action("MyAction", "Controller", new {label = Model.?}, null)';
        window.location = theUrl;
    }
</script>

Controller:

 public ActionResult MyAction(string label)
        {
            //Update the model and send it to the Database
            return View();
        }

My problem is, that I have an enumeration of models, so I need to pass a special model to the javascript method, as the controller itself needs to now the id of the model to update the correct model. Additionally I need to now the actual status of the checkbox (checked or unchecked) in the controller. How can I achieve this? Or is there a possibility to call the controller method I want to call directly in the HTMLHelper without javascript?




Aucun commentaire:

Enregistrer un commentaire