Ian Caparanga Ian Caparanga - 3 months ago 12
C# Question

MVC Model property not updated when accessed in javascript

I have this in my cshtml file:

@for (var i = 0; i < Model.Vehicles.Count; i++){
@Html.CheckBoxFor(m => Model.Vehicles[i].Selected)}


Basically Model.Vehicles is a List of vehicles and the Selected property is a bool...

I have a button that when clicked, calls this function:

function delSel(){
var vehicles = '@Html.Raw(Json.Encode(Model.Vehicles))';
var selIDs = "";
for(var i = 0; i < vehicles.length; i ++)
{
if (vehicles[i].Selected == "true") {
selIDs = selIDs + vehicles[i].ID + ",";
}
}
document.getElementById('CRVehicleIDs').value = selIDs;
}


My problem is, eventhough the Checkbox is checked, the value of the Selected property is always equal to false... Is there a better way to get the selected items in this case?

Answer
var vehicles = '@Html.Raw(Json.Encode(Model.Vehicles))';

This will not work as you are expecting, the razor syntax is rendered server side which means the value of this will not get updated when a user clicks on the checkboxes.

What you can do however is when you create you're checkboxes, give them an ID using i variable in your for loop.

@Html.CheckBoxFor(m => Model.Vehicles[i].Selected, new { id = "checkbx_" + i })

Then you can iterate through your checkboxes with a for loop.

function delSel(){
    var vehicles = @Html.Raw(Json.Encode(Model.Vehicles));
    var selIDs = "";
    for(var i = 0; i < vehicles.length; i ++)
    {
        if (document.getElementById('checkbx_' + i).checked) {
            selIDs = selIDs + vehicles[i].ID + ",";
        }
    }
    document.getElementById('CRVehicleIDs').value = selIDs;
}