Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick in ASP.NET MVC razor CheckBoxFor not working

I need to assign an onclick event to a CheckBoxFor in ASP.NET MVC razor, but it is never called.

I have something like this, which does not work:

<script type="text/javascript">
    function setCompleteStatus() {
        alert("setCompleteStatus called");
    }
</script>

@Html.CheckBoxFor(m => m.Process.IsComplete, 
                  new Dictionary<string, object>{
                     {"id", "p1isCompleted"}, 
                     {"onclick","setCompleteStatus()"}, 
                     {"data-role", "flipswitch"}, 
                     {"data-on-text", "complete"}, 
                     {"data-off-text", "incomplete"}, 
                     {"data-wrapper-class", "custom-size-flipswitch"}})

This attempt also doesn't work:

<script type="text/javascript">
    $("#p1isCompleted").click(
        function setCompleteStatus() {
            alert("setCompleteStatus called");
        }
    );
</script>

This approach leads to the alert being called once when the page is loaded but not when I click on the checkbox:

<script type="text/javascript">
    $(document).ready(
        $("#p1isCompleted").click(
            alert("setCompleteStatus called");
        )
    );
</script>

Because of the data- attributes I cannot use a dictionary like this: new {@onclick, "setCompleteStatus('1')"}

By the way, there are no javascript errors displayed in Firefox's console

like image 829
Lyndon Avatar asked Nov 30 '22 11:11

Lyndon


2 Answers

In MVC, use underscore(_) instead of Hyphen(-) for data* attributes

Just pass the html attributes parameter as anonymous object shown below for CheckBoxFor.

 @Html.CheckBoxFor(m => m.Process.IsComplete, 
              new {
                   @id="p1isCompleted", 
                   @onclick="setCompleteStatus()", 
                   @data_role="flipswitch",
                 }
like image 25
Murali Murugesan Avatar answered Dec 10 '22 21:12

Murali Murugesan


You can do it by modify your {"onclick", "setCompleteStatus()"} code to {"onclick","setCompleteStatus.call(this)"} and get advantage of this variable. It should be like this:

@Html.CheckBoxFor(m => m.Process.IsComplete,
                  new Dictionary<string, object>{
                     {"id", "p1isCompleted"},
                     {"onclick","setCompleteStatus.call(this)"},
                     {"data-role", "flipswitch"},
                     {"data-on-text", "complete"},
                     {"data-off-text", "incomplete"},
                     {"data-wrapper-class", "custom-size-flipswitch"}})

<script type="text/javascript">
    function setCompleteStatus() {
        alert(this.checked);
    }
</script>
like image 108
Adiono Avatar answered Dec 10 '22 22:12

Adiono