The dropdown list will not select the value I need
Dictionary<int,int> RowDict = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
{
RowDict.Add(i, i);
}
var rows = new SelectList(RowDict, "Key", "Value", 6);
ViewBag.Rows = rows;
here is the code in the view:
<div class="editor-label">
@Html.LabelFor(m => m.Rows)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.Rows, (SelectList)ViewBag.Rows)
@Html.ValidationMessageFor(m => m.Rows)
</div>
When I run the code 6 is not selected. Can you see any errors in this code? The first value is selected.
m => m.Rows suggests there is a model involved. It works better if you do the initialization with the rows from the model, not the view bag.
A really quick and dirty initialization like this :
And this in the controller where the view is requested :
And a view starting with something like :
…
makes it work. You can adapt this code and initialization the way you want, as long as you remember that models are passed by value to the view, reason why I setup my init in the constructor (every time a TestModel is created, the Select List will get initialized).
Also you can make a mix of viewbag and model and have it to work, I wouldnt recommend it for readability.