Using Html.DropDownListFor() with a SelectList

2019-09-11 07:23发布

问题:

What is the correct way to populate a SelectList when using the Html.DropDownListFor helper in ASP.Net MVC 3?

I basically have a "Create" form which I want to specify the entry values on for a particular field. For example, it is a movie database and I want the ability to enter a Genre, but I don't want users to be able to enter what they like, so I assume a SelectList to be the best answer?

A way that works is to create a new class with a static method to return the SelectList:

public class Genres
{
    public static List<string> GetGenres()
    {
        List<string> myGenres = new List<string>();
        myGenres.Add("Comedy");
        myGenres.Add("Romantic Comedy");
        myGenres.Add("Sci-Fi");
        myGenres.Add("Horror");

        return myGenres;
    }
}

Which can then be used like this:

    <div class="editor-field">
        @Html.DropDownListFor(model => model.Genre, new SelectList(OLL.Models.Genres.GetGenres()))
    </div>

It just doesn't seem like the right/easiest way to do it? I think I'm missing something obvious here...

Thanks for any assistance you can provide.

回答1:

This is a simple selectList style I use for drop downs all the time, hopefully you find this helpeful.

 ViewBag.AlbumListDD = from c in db.Query<DatabaseEntities.VenuePhotoAlbum>("WHERE VenueId = @0", VenueId)
                      select new SelectListItem
                      {
                         Text = c.Name,
                         Value = c.Id.ToString()
                      };

Inside my view:

@Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.AlbumListDD, new { id = "ChangeAlbum" })

Hopefully you can find this useful as this is a database route to go. I typically like to have all of that sort of information in a database and that way users can dynamically add/remove and change these dropdown items at will. There is a bit of SQL work behind the scenes required when removing a type but it has proven to be very successful and fast for me at this point.



回答2:

 var og = (from s in DB.Products
 select new SelectListItem
  {
        Text = s.ProductName,
         Value = s.ProductID.ToString()
  }); 
  ViewBag.lstProducts = new SelectList(getproductname, "ProductID", "ProductName");
<p>
    @Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.lstProducts, new { @id = "drp" });
</p>