1

I have a Yes/No drop-down declared as follows:

@Html.DropDownListFor(model => Model.Items[i].ITEM_PAYS, Model.YesNoSelectList, new { @class = "allow-edit" })

Where Model.YesNoSelectList is set up as follows in my BoqReviewViewModel class:

public BoqReviewViewModel()
{
    YesNoSelectList = new SelectList(new[]
        {
            new {Text = "Yes", Value = true},
            new {Text = "No", Value = false},
        },
        "Value",  "Text");
}
public SelectList YesNoSelectList { get; set; }

This results in an element rendered as follows:

<select class="allow-edit" id="Items_0__ITEM_PAYS" name="Items[0].ITEM_PAYS">
    <option value="True">Yes</option>
    <option value="False">No</option>
</select>

Yet even when the model property for the select, i.e. Model.Items[i].ITEM_PAYS is false, the drop-down still shows Yes.

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • So the code you have there will render the list the way you're showing it. Correct me if I'm wrong but nothing selects Yes or no in the html. It renders them and basically selects the first one which is yes. If you want something like a 'Please select', you should generate another option that's selected and disabled at the same time on load or else it selects Yes by default because it's first. – Jabberwocky Jun 26 '19 at 12:58
  • Check this. yes is preselected because you're not rendering something beforehand. https://jsfiddle.net/7zbuvk9d/ .All in all your code doesn't decide what to select. It just renders. – Jabberwocky Jun 26 '19 at 13:00
  • @Jabberwocky I have always understood `@Html.DropDownFor` to render and set the value properly, it has always before when I have used it. I have not simply coded the shown HTML for the `select`, it was rendered by `@Html.DropDownFor`, which should set the model value as far as I know. – ProfK Jun 26 '19 at 13:03
  • Have you checked this? https://stackoverflow.com/questions/19476530/html-dropdownlistfor-selected-value-not-being-set You're right it's supposed to be sending a value in, BUT I don't think you're actually setting a value anywhere. That's why it preselects Yes – Jabberwocky Jun 26 '19 at 13:05
  • @Jabberwocky Thanks for all the help. I have found that if I create the `SelectList` in the Razor markup I can set the selected value there, and it seems to work fine.Why not suggest that, as shown in your last question link, as an answer and I'll accept. – ProfK Jun 26 '19 at 13:21
  • Sure, will do in a second. Glad I could help – Jabberwocky Jun 26 '19 at 15:09

1 Answers1

0

You should create the SelectList in the Razor markup so you can set the selected value there.

The way it is now, the Html helper won't select anything and renders the first option as preselected.

Jabberwocky
  • 768
  • 7
  • 18