user3557236
user3557236

Reputation: 299

Dropdownlistfor selected item not selecting using viewbag

I have dropdownlistfor which is getting populated from viewbag string array

 <td>@Html.DropDownListFor(m => Model[i].start_operation, new SelectList(ViewBag.ValidOpers))</td>
 <td>@Html.DropDownListFor(m => Model[i].end_operation, new SelectList(ViewBag.ValidOpers))</td>  

It is not selecting the selected item based on Model[i].start_operation and end_operation

ViewBag.ValidOpers = new[] { "One", "Two", "Three", "Four"};

Unable to figure out why it is not selecting. I check giving just a Html.DisplayFor(m=>Model[i].start_operation to check if it is getting the values and yes it is getting the value and displaying correctly in the label, but the same value is not getting selected in the dropdownlistfor.

Upvotes: 1

Views: 971

Answers (1)

JosephDoggie
JosephDoggie

Reputation: 1594

To over-answer your question:

Try first adding a not-mapped member to your model class:

e.g.

   [NotMapped]
   static public List<SelectListItem> myListOptions { get; set; }

then in the controller you can have

MyNameSpace.Models.MyModel.myListOptions = db.myTable.Select(uA=> new SelectListItem{ Value = uA.myColumn, Text = uA.myColumn}).Distinct().OrderBy(uA=>uA.Text).ToList();

// if you want string constants use:

        MyNameSpace.Models.MyModel.myListOptions  = new List<SelectListItem>();

        MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "a", Value = "a"});
        MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "b", Value = "b" });

then in the view, you use:

    <div class="editor-field">
       @Html.DropDownListFor(model => model.myField, MyNameSpace.Models.MyModel.myListOptions )
       @Html.ValidationMessageFor(model => model.myField)
    </div>

Upvotes: 1

Related Questions