E.R Pfaff
E.R Pfaff

Reputation: 19

Setting a checkbox value within a model list (MVC)

I have the following in MVC:

Area of Impact:

    @for (int i = 0; i < Model.ImpactAreas.Count; i++)
    {
        @Html.HiddenFor(m => m.ImpactAreas[i].ImpactAreaID)
        @Html.HiddenFor(m => m.ImpactAreas[i].Name)
        @Html.HiddenFor(m => m.ImpactAreas[i].Description)
        @Html.HiddenFor(m => m.ImpactAreas[i].IsActive)
        @Html.HiddenFor(m => m.ImpactAreas[i].ConcurrencyDateTime)
        @Html.HiddenFor(m => m.ImpactAreas[i].InsertedDateTime)
        @Html.HiddenFor(m => m.ImpactAreas[i].Checked)
    }

    @foreach (var area in Model.ImpactAreas)
    {
        CurrentImpactArea = area.Name;
        string myImpactAreaName = "ImpactArea" + CurrentImpactArea;
        <div class="columns large-2 medium-3 small-4">
         <input type="checkbox" @area.Checked name="@myImpactAreaName" value="@area.ImpactAreaID" @(area.ImpactAreaID == Model.ImpactAreaID ? " checked='checked'" : "") /><label title="@area.Description" for="ImpactAreaID">@area.Name</label>
        </div>
    }
</div>

I am trying to get the checkbox to set the value in the list item with the checkbox checked status (true/false) in the impact area object:

public bool Checked {  get; set; }

however in my main object, I have a list of the above object

Any help?

Upvotes: 1

Views: 2467

Answers (2)

user3559349
user3559349

Reputation:

You first for loop is correctly generating the form controls for your model, but you have hidden input for the Checked property which renders the initial value of the property, and its that value which will be bound when you submit the form (your just sending back the original data you sent to the view.

Your second foreach loop is generating form controls which have no relationship to your model and will not bind to your model (refer this answer for more details of why using a foreach loop will not work)

In addition, your degrading performance by rendering all those hidden inputs and sending them all back again unchanged. Use a view model containing only 2 properties - ImpactAreaID and Checked and when you submit the form, get the records from the database based on the ID property, update the records Checked property based on the view model and save it (refer What is ViewModel in MVC?).

Your view code just needs to be

@for (int i = 0; i < Model.ImpactAreas.Count; i++)
{
    @Html.HiddenFor(m => m.ImpactAreas[i].ImpactAreaID)
    @Html.CheckBoxFor(m => m.ImpactAreas[i].Checked)
    // assumes you want the Name value to be used as the label for the checkbox
    @Html.LabelFor(m => m.ImpactAreas[i].Checked, Model.ImpactAreas[i].Name)
}

Upvotes: 1

Emil
Emil

Reputation: 281

try this

<input type="checkbox" name="@Model.name" id="@Model.name" @(Model.Checked ? "checked" : "") />

Upvotes: 0

Related Questions