问题
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.
回答1:
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"} })
回答2:
User Html.DropDownList
instead of Html.ListBox
to create a single select box.
回答3:
Well, I've sort of got an answer to question one - turns out it's the browser that changes the rendering from simple list to dropdown list if "multiple" is removed, so I'm going to have to be creative to solve that one.
Question Two remains - why doesn't Razor keep my selected value during rendering?
来源:https://stackoverflow.com/questions/5438798/how-to-create-a-single-select-list-box-that-shows-the-selection-using-razor