Kye
Kye

Reputation: 6239

MVC list is null on postback

I'm working on an MVC application where I'd like to use Select2 and optgroups within a HTML Select, so I need a little more control than what Html.DropdownlistFor can provided.

In my view I have,

   <select class="form-control">
                        @for (var i = 0; i < Model.Certs.Count; i++)
                        {
                            <option id="@Model.Certs[i].Value" value="@Model.Certs[i].Value">@Model.Certs[i].Text</option>
                        }
                    </select>

In the Model

 public List<SelectedRecord> Certs { get; set; }

Yet for some reason, the list is always null on the parent Model when posted back to the server. I've tried the "for" method instead of foreach, and the editTemplates approach. Nothing seems to be working. Am I missing something obvious?

Upvotes: 1

Views: 212

Answers (2)

Navneet
Navneet

Reputation: 447

in id attribute there is no need of value @Model.Certs[i] Create right id and u will get the value in list after post also.

 <select class="form-control">
                        @for (var i = 0; i < Model.Certs.Count; i++)
                        {
                            <option id="@Model.Certs[i]" value="@Model.Certs[i].Value">@Model.Certs[i].Text</option>
                        }
                    </select>

Upvotes: 0

theLaw
theLaw

Reputation: 1291

This is normal, the list is not serialized on postback the solution is to put the list in a TempData and retrieve the list in the post.

For the selected options i suggest to put and id and a name to the your select like "Sel"

<select name="Sel" id="Sel"> ... </select>

and put that in your model like

public string Sel { get; set;}

so in your post you'll get the selected options

Upvotes: 1

Related Questions