views:

324

answers:

2

I'm new in ASP.NET MVC 2 and 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".

A: 

msdn: http://msdn.microsoft.com/en-us/library/ee703573.aspx

an example usage: http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value

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")) %>
ewwwyn
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 :s
Rinesse
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?
ewwwyn
a static list which contains 4 options not frop a data base
Rinesse
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. :)
ewwwyn
I'll try it now:). thank you a lot :)
Rinesse
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 :/
Rinesse
A: 
<%: 
     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.

Berat