Wizard-of-Koz
Wizard-of-Koz

Reputation: 1787

Adding to a List of objects from the View

What I wanted to do was seeming simple but I am having a bit of trouble. I've created the following class:

// SelectedItem.cs
public class SelectedItem
{
    public Brand Brand { get; set; }
    public string Model { get; set; }
}

In my view page I've created a list of SelectedItem:

// Chart.cshtml
@model Prediction.Models.Chart.ManualSelection
@{
    @using Prediction.Models.Chart
     List<SelectedItem> selectedItems = new List<SelectedItem>();
}

And I'm trying to add to this list from the html in my view. I've created a table that has its rows populated by a foreach loop.

// Also Chart.cshtml, below the previous code section where I created the list
<table class="table table-borderless table-hover table-striped table-sm mb-0">
    <tbody>
        @foreach (var item in Model.PhoneInfo)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Brand)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Model)
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-link">Select</button>
                </td>
            </tr>
        }
    </tbody>
</table>

Essentially what I'm trying to do is when the button is clicked, I want that specific item.Brand and item.Model to be added to List<SelectedItem> selectedItems.

Upvotes: 1

Views: 53

Answers (1)

Roman.Pavelko
Roman.Pavelko

Reputation: 1665

Unfortunately this is impossible. Like it was mentioned in the comment, this list exists only in the scope of rendering view on the server, before sending to the client's browser. In order to save your item.Brand and item.Model you need to use JavaScript, that will be executed in browser on client side or you can send this information back to the server and process it there.

Upvotes: 1

Related Questions