mercredi 20 juin 2018

Can't bind checkbox in partial view to the main model (MVC)

I've been running into to issue and I've been searching for an answer but nothing helped.

I have a Model:

public class Filters
{
    public bool Filter1 { get; set; }
    public bool Filter2 { get; set; }
    public bool Filter3 { get; set; }
    etc...
}

I have a partial view with multiple checkboxes and tried multiple things:

<input id="Filter1" name="Filter1" type="checkbox" value="true">
<input type="hidden" value="false" name="Filter1" />

and

@Html.CheckBoxFor(model => model.Filter1)

Then I have a main model:

public class Dashboard
{
    ...
    public Filters FiltersDashboard { get; set; }
}

And somewhere in the main view I insert the partial view like this:

@Html.EditorFor(model => model.FiltersDashboard, "Filters")

In a jquery, I execute an alert when the checkbox is clicked and shows the value of the checkbox. This value remains unchanged.

<script>
    $("#Filter1").click(function () {
        alert(" @Model.FiltersDashboard.Filter1 ")
    });
</script>

This tells me that something isn't correctly bound but I have no clue what I'm doing wrong.

Also, the reason I'm not using a checkboxlist is because I need to execute a different query for each filter so I need specific names and bindings for them.




Aucun commentaire:

Enregistrer un commentaire