Ian Caparanga
Ian Caparanga

Reputation: 33

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?

Upvotes: 1

Views: 732

Answers (2)

Ryan Searle
Ryan Searle

Reputation: 1627

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;
}

Upvotes: 1

Dai
Dai

Reputation: 155055

You're rendering this.Model.Vehicles to JSON which is then rendered within Javascript single-quotes - this will likely result in invalid Javascript syntax when accessed in a browser because JSON object property names are also enclosed in quotes.

Remove the quotes around @Html.Raw.

You would have spotted this if you looked at the rendered HTML of the page and saw that a large chunk of it would be covered in syntax errors.

Other tips:

  • JavaScript is typically styled with the opening brace on the same line as the keyword (as with Java), not the line below (as C#). It's also customary to use camelCase for JavaScript objects, not TitleCase. You should be able to customize your JSON-generator to use camelCase, refer to the documentation.
  • Boolean properties tend to be prefixed with Is, so it would be IsSelected (or isSelected in camelCase).
  • This is suboptimal:

    if( vehicles[i].Selected == "true" ) {
    

    Assuming that the Selected property is rendered as Javascript boolean value, you need only act on it directly:

    if( vehicles[i].Selected ) {
    

Upvotes: 0

Related Questions