I have in my view model, a comma separated string:
vm.colours = "black, white, blue, green"
In my Razor page, I want to show a drop down list, so I have:
@Html.DropDownList(m => m.colours, new SelectList(Model.colours))
However, this gives me a select list item for every LETTER in the string.
Is there any way I can amend this, to give me a select list item for each colour?
Thank you,
Mark
At the moment you just send a string, which is just an array of characters, so in this context it's interpreted as such. Use Split
method to separate the elements you want.
Edit:
Check this answer for code example of using Split
in this case.
@Html.DropDownList(m => m.colours, new SelectList(Model.colours))
No overload of DropDownList
accepts an expression. For that code to work you need to do it like this:
Html.DropDownList("give_it_a_name", new SelectList(Model.colours))
Or perhaps you mean to use DropDownListFor
, if yes then you need two things:
Your view should look like this:
public class YourVM
{
public string SelectedColor{get;set;}
public IEnumerable<string> Colors {get;set;}
}
You need to have something like this in your controller:
var colors = "black, white, blue, green";
vm.colours = colors.Split(',');
And finally in your view:
@Html.DropDownListFor(m => m.colours, new SelectList(Model.Colors))
Well, it looks like colours is not an IEnumerable<string>
but just a string
. As the SelectList
will enumerate over the object passed into, that means in this case an enumeration over a string which returns all characters. Please try it using a string array:
vm.colours = new string[] { "black", "white", "blue", "green" };
The call to Html.DropDownList
remains the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.