[英]Creating a Drop Down list from a ViewModel in MVC 4
我是MVC 4的新手,我正在尝试创建一个下拉列表,它使用我从sql中提取的数据库中的多个表。 他们将汽车的模型和颜色都放在不同的表格中。
继承我的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; }
}
}
这是我的控制器
public ActionResult DealerInventory()
{
InventoryViewModel viewModel = new
InventoryViewModel();
viewModel.Colors = db.Colors.ToList();
viewModel.Make = db.Makes.ToList();
viewModel.Model = db.Models.ToList();
return View();
最后这是我的观点...我不确定这是否是正确的方法,因为这是什么给我一个错误
@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>
我对此很新! 任何帮助都会很棒
首先,如果您的模型中没有捕获下拉所选值的机制,我不明白为什么需要下拉列表。 所以我首先将您的模型修改为:
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; }
}
然后,我将做一个扩展方法,将任何IEnumerable转换为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);
}
}
}
然后在我看来,我会让这一行生成一个下拉列表:
@Html.DropDownListFor(m => m.ColorId, Model.Colors.ToSelectList("ColorId", "ColorName"), "-- SELECT --")
假设您的Color类具有ColorId和ColorName属性...
控制器 -
var PayList = db.Pay.ToList();
ViewBag.PayList = new SelectList(PayList, "Id", "Name");
查看 -
@Html.DropDownList("Pay", ViewBag.PayList)
这是在剃须刀中使用HTML扩展绑定Dropdown的正确方法。 您还应该签出@Html.DropDownListFor
需要有关错误的更多详细信息,还要将循环更改为:
@foreach (var item in Model.Make){
<option value="@item.MakeDescription">@item.MakeDescription</option>
}
Ditch ViewBag并使用强类型模型
@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);
}
这是模型属性,最好在构造函数中实例化它。
public List<SelectListItem> LeagueSL { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.