简体   繁体   中英

Creating a Drop Down list from a ViewModel in MVC 4

I'm very new to MVC 4 and I'm trying to create a drop down list that uses multiple tables from my database that I pulled from sql. They're make models and colors of cars all in different tables.

Heres my ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Car_ProjectKW.Models;

namespace Car_ProjectKW.ViewModels

{
public class InventoryViewModel
{
    public List<Color> Colors { get; set; }
    public List<Make> Make { get; set; }
    public List<Model> Model { get; set; }
}
}

Here is my Controller

public ActionResult DealerInventory()
    {
        InventoryViewModel viewModel = new
        InventoryViewModel();
       viewModel.Colors = db.Colors.ToList();
       viewModel.Make = db.Makes.ToList();
       viewModel.Model = db.Models.ToList();


        return View();

and finally here is my view... I'm not sure if this is the proper way to do it because this is what's throwing me an error

@model Car_ProjectKW.ViewModels.InventoryViewModel 
       @{
           ViewBag.Title = "DealerInventory";
       }

<h2> Drop Down</h2>
<div>
@*Html.DropDownList("Make")*@
<select>
    @{foreach (var item in Model.Make){
          <option value="@item.MakeDescription">@item.MakeDescription</option>

    }}
</select>
</div>

I'm very new to this! any help would be great

First off I don't see why do you need drop downs if there is no mechanism in your model to capture the drop down selected values. So I would 1st modify your model to something like:

public class InventoryViewModel
{
   public int ColorId { get; set; }
   public int MakeId { get; set; }
   public int ModelId { get; set; }
   public List<Color> Colors { get; set; }
   public List<Make> Make { get; set; }
   public List<Model> Model { get; set; }
}

Then I would make an extension method to convert any IEnumerable to a SelectList:

namespace System
{
   public static class SelectListExtensions
   {
      public static SelectList ToSelectList<T>(this IEnumerable<T> items, string dataValueField, string dataTextField) where T : class
      {
         return new SelectList(items, dataValueField, dataTextField);
      }
   }
}

And then in my view I would have this line to generate a drop down:

@Html.DropDownListFor(m => m.ColorId, Model.Colors.ToSelectList("ColorId", "ColorName"), "-- SELECT --")

assuming your Color class has properties ColorId and ColorName...

Controller -

   var PayList = db.Pay.ToList();
 ViewBag.PayList = new SelectList(PayList, "Id", "Name");

View -

@Html.DropDownList("Pay", ViewBag.PayList)

This is the proper way of binding a Dropdown using Html Extensions in razor. You should also check out @Html.DropDownListFor

Need more details on the error, also change your loop to this:

 @foreach (var item in Model.Make){
          <option value="@item.MakeDescription">@item.MakeDescription</option>

    }

Ditch ViewBag and use a strongly typed model

 @Html.DropDownListFor(x => x.LeagueId, Model.LeagueSL, "--Select League--", new { id = "ddlLeague"})

public ActionResult Index()
    {
        BaseballViewModel model = new BaseballViewModel();

        using (BaseballEntities context = new BaseballEntities())
        {
            var leagueList = context.League.ToList();

            foreach (var item in leagueList)
            {
                model.LeagueSL.Add(new SelectListItem() { Text = item.LeagueName, Value = item.LeagueId.ToString() });
            }

        }
        return View(model);
    }

Here's the model property, it is best to instantiate it in the constructor.

 public List<SelectListItem> LeagueSL { get; set; }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM