Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a single select list box that shows the selection using Razor

How do I create a simple, single select list box using the Razor view engine? I'm currently running into two problems. The first is that the list box "Select" code generated has 'multiple' automatically added. Question One is how to turn that off. No, I don't want to have to use a drop down list box.

Question Two is trickier. The generated "Select" in the output html does not show any items as being selected, despite the item in question have selected values. Here's my code:

Object model:

public class Description
{
    public String code { get; set; }
    public SelectList codelist;
}

Controller:

code = "drain";
codelist = new SelectList(sourcelist, "Key", "Value", "drain");

View:

@Html.ListBoxFor(model => model.code, Model.codelist)

Output HTML:

<select data-val="true" data-val-required="The Select the permit type to apply for field is required." id="code" multiple="multiple" name="code"><option value="drain">Interior Drain Repair</option>
... yadda yadda yadda
</select>

You can see my two problems here. First, "multiple" has been added to the select list, and the selected option "drain" is not selected.

Any suggestions? I'm at the point of just tossing Razor and hand coding this stuff.

like image 535
Steve G Avatar asked Oct 28 '25 08:10

Steve G


1 Answers

To create a single select list box you can use DropDownListFor but set a size attribute... so do this:

@Html.DropDownListFor(model => model.code,
         Model.codelist, 
         new Dictionary< string, object >() { { "size", "3"} })
like image 162
Donuts Avatar answered Oct 30 '25 10:10

Donuts