How to write a simple Html.DropDownListFor()?
Asked Answered
S

7

147

In ASP.NET MVC 2, I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".

Siracusa answered 16/6, 2010 at 23:21 Comment(0)
I
201

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>
Involved answered 16/6, 2010 at 23:35 Comment(7)
that really clear. I'd like to know where should I put the IEnumerable<Color> in my code? I know it seems stupid as question but I'm very lost and new in it :sSiracusa
No worries, friend. I know how it feels. :) As you suggested in your initial question, is this a static list that you're going to create in code, or are you going to be pulling this list from a database?Involved
a static list which contains 4 options not frop a data baseSiracusa
Create a static class called "HtmlLists" or something. Place the static class in the System.Web.Mvc namespace. In your static class, add your static list of IEnumerable<Color> Colors. Then, on your view, you can reference it by calling HtmlLists.Colors. Hope that makes sense. Let me know. :)Involved
I didn't know how to do it :'(... I dont know where to put the Color classe and the HtmlLists (in models folder may be?) and how to referes in the view. aloso a dont know how to put the result of the liste in an attribut of the viewModel..I'm so confused :/Siracusa
love the static list!Lammas
See this one. Good approach when entities involved: #21879173Promotion
Y
70
<%: 
     Html.DropDownListFor(
           model => model.Color, 
           new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red"  },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"}
                    },
                  "value",
                  "text",
                   Model.Color
           )
        )
%>

or you can write no classes, put something like this directly to the view.

Yuma answered 3/10, 2010 at 3:59 Comment(2)
I recieve below error when try your code : "Object reference not set to an instance of an object."Flaunch
bad idea to add model logic to your viewJosefajosefina
P
38

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))
Pavilion answered 1/5, 2012 at 2:53 Comment(0)
T
35

Hi here is how i did it in one Project :

     @Html.DropDownListFor(model => model.MyOption,                
                  new List<SelectListItem> { 
                       new SelectListItem { Value = "0" , Text = "Option A" },
                       new SelectListItem { Value = "1" , Text = "Option B" },
                       new SelectListItem { Value = "2" , Text = "Option C" }
                    },
                  new { @class="myselect"})

I hope it helps Somebody. Thanks

Trix answered 14/3, 2014 at 15:0 Comment(0)
N
12

Or if it's from a database context you can use

@Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
Nez answered 10/5, 2014 at 19:53 Comment(10)
First of, sorry for any grammar incorrections since english is not my first language. It's always nice to see someone make such a thought-through comment, I applaud you sir that you took the time to contribute. It's also always reassuring that the profession of developers is in such good hands as yours, since mine won't do. The likes of your ignorant comment is why I never post here anymore. May I inform you that when I wrote this I was 8 months in my education and had never touched Web Development beforehand. I wanted to share a different aproach to with the little knowledge I had.Nez
8 months in? Then why try to solve problems when you could not know how? My comment is far from ignorant, I see this stuff day in and day out. You have to start considering the amount of manual work you are obligating to your colleagues. imagine you have an enterprise application with hundreds of views and your CTO wants to switch to Oracle DB. Imagine the literal cost of refactoring all of the views and controllers that use drop down lists just because of your one line of code! I am not trying to insult you, just trying to explain to you how a little bad advice can have huge effects.Pelasgian
No different to needing to refactor the static enum based solutions. At least it wasn't a code change every time the business wanted to add a colour to the list. If more people thought about actually using a database the world would be a better place.Variorum
I confirm this solution is sometimes way better, datas can change anytimes where i work so nothing is like direct db, i don't have to code back when they mess up.Tolmann
@Variorum You're completely missing JBeckton 's point - he's saying if you are getting data from a database then add additional layer(s) so that the database is not referenced in the viewApologize
@Sean T Patterns are great. Until they aren't. It's always better to let the developer who's doing the work make the call instead of ranting to the world about how the way they're doing it hurts your feelings.Variorum
@Variorum Generally I agree, but not when the developer is inexperienced, as was the case here. It's just creating work further down the line for a more experienced dev to refactor at a later date. In no serious application would you reference the database in a view.Apologize
@Sean T "In no serious application would you reference the database in a view." this is just an opinion and one that has many flaws. Here's my countering opinion... The primary reason for creating as many layers as possible between database and the front end is that most .net developers are mortally afraid of databases. That's from a long time database developer. And don't use the testing abstraction excuse. Most testing only tests that the layers aren't broken and not that the application manipulates the data properly which ultimately is the primary purpose of the application.Variorum
@Variorum You're wrong mate. I'll give you a concrete example to make things more clear. Views are meant to be re-usable, if I have a view that's repeated n times on the page, that's n calls to the database for EACH drop down list that you've put a query in to get the options. Now if we abstract it out into a ViewModel, we can reduce this to 1 database call for however many views we want. This is before even going into the clear maintainability advantages of not having to scour through all views if the data source ever changes. ".net developers are mortally afraid of databases" - what?Apologize
Well this thread brings a smile to my face when I visit it every once in a while. I understand @SeanT point a little more better. I guess I just felt attack in general when I was trying to help. I prefer to myself nowdays to keep everything separated by layers, and not letting anything touch the view unless its separated into ViewModels. Its just how I like doing it myself. I apreciate m12lrpv taking me in defence thou :-)Nez
N
7

With "Please select one Item"

@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
  new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
    .Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
  new { @class = "myselect" })  

Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://mcmap.net/q/80326/-joining-two-lists-together JaredPar ;

Thanks Master Programmer && Joel Wahlund && JaredPar ;

Good luck friends.

Navigable answered 8/6, 2014 at 22:44 Comment(0)
S
4
@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

Strobe answered 16/9, 2018 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.