0

I am trying to pass the state of multiple checkboxes as a string (updated by JS when someone checks a box) when a form is submitted, rather than iterate through each value in the controller. What am I doing wrong? I tried:

@model UserClaimsViewModel;

<script>
  function callme(val) {
    var t = "";
    $('#MyDiv input:checked').each(function () {
      t += this + ",";
    });
    @Model.CoIDs=t;
    @Html.HiddenFor(m => m.CoIDs);
      console.log("coids updated to: " +@Model.CoIDs);
  }
</script>


@Model.email
<br />
@using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.email) 
    <div class="panel-body" id="MyDiv">
        <table>
            @foreach (var t in Model.CoIDs.Split(','))
            {
                <tr>
                    <td>
                        <input type="checkbox" onchange="callme(@t)" name="@t" id="@t">@t
                    </td>
                </tr>
            }
        </table>
    </div>
    <input type="submit" value="Submit Changes" />
}

Error:

UserClaimEditView?userEmail=a@gmail.com:78 Uncaught ReferenceError: Invalid left-hand side in assignment

Error after checking checkbox:

UserClaimEditView?userEmail=a@gmail.com:65 Uncaught ReferenceError: callme is not defined at HTMLInputElement.onchange (UserClaimEditView?userEmail=a@gmail.com:65)

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • `callme(val)`: you are never using `val`, why? – Marco May 15 '18 at 21:11
  • @Marco, Im using it via `this` am I not? – Rilcon42 May 15 '18 at 21:31
  • You code is riddled with errors. First `this` refers to the checkbox element, not its value. Your `@Model.CoIDs=t;` makes no sense, and look at the actual html you are generating to understand. And razor is server side code while jQuery is client side code so you cannot update a server side variable with a javascript variable anyway. –  May 15 '18 at 23:14
  • Then there is the waste of resources by trying to build the string every time a checkbox is toggled, instead of just once when the form is submitted. And in any case you are now sending twice as much data back to the server. Do this property by generating view model to represent what you want and generate a checkbox list (refer [this answer](https://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) for an example –  May 15 '18 at 23:18

0 Answers0