控制器代码:
AccountsDetailsViewModel vOwnerVM = Mapper.Map<VehicleOwner, AccountsDetailsViewModel>(vOwner);
AccountsDetailsAccountViewModel vOwnerDetailsVM = Mapper.Map<VehicleOwner, AccountsDetailsAccountViewModel>(vOwner);
ViewBag.FleetType = new SelectList(VehicleOwnerFleetTypeFactory.GetTypes().OrderBy(l => l.Type), "Id", "Type");
vOwnerVM.AccountDetails = vOwnerDetailsVM;
主要ViewModel代码:
public class AccountsDetailsViewModel
{
public AccountsDetailsAccountViewModel AccountDetails { get; set; }
}
主视图代码
@model X.Views.Accounts.ViewModels.AccountsDetailsViewModel
@Html.Partial("DetailsAccount", @Model.AccountDetails)
部分ViewModel代码:
[DisplayName("Fleet Type")]
public int FleetType { get; set; }
部分查看代码
@model X.Views.Accounts.ViewModels.AccountsDetailsAccountViewModel
@Html.DropDownListFor(model => model.FleetType,
(IEnumerable<SelectListItem>)ViewBag.FleetType)
@Html.DisplayFor(model => model.FleetType) (FOR DEBUG)
VehicleOwnerFleetType类
public class VehicleOwnerFleetType
{
public int Id { get; set; }
public string Type { get; set; }
}
public class VehicleOwnerFleetTypeFactory
{
static readonly VehicleOwnerFleetType[] Types = new VehicleOwnerFleetType[] {
new VehicleOwnerFleetType() {Id = 0, Type = "Unknown"},
new VehicleOwnerFleetType() {Id = 1, Type = "HGV"},
new VehicleOwnerFleetType() {Id = 2, Type = "Car"},
new VehicleOwnerFleetType() {Id = 3, Type = "Van"},
new VehicleOwnerFleetType() {Id = 4, Type = "Mixed"}
};
public static VehicleOwnerFleetType[] GetTypes()
{
return Types;
}
public static VehicleOwnerFleetType GetType(int id)
{
return Types.FirstOrDefault(m => m.Id == id);
}
}
无论数据库显示什么,下拉列表都不会显示模型中的正确值,只会显示列表中的最高值。
但是,如果我选择一个值然后提交表单以将更改保存到数据库,它会提交正确的值。
当在控制器中返回viewmodel的视图时,这些值完全镜像了数据库,我无法弄清楚它为什么会这样做。
编辑:&#39;部门&#39;下拉列表是唯一一个自动选择正确值的内容。
答案 0 :(得分:2)
问题可能是因为您的选择列表和您的VM的成员变量具有相同的名称。
model.FleetType
和
(IEnumerable<SelectListItem>)ViewBag.FleetType
尝试将选择列表重命名为FleetTypeList或类似的
答案 1 :(得分:1)
对我来说很好。检查您是否将模型传递给视图。
@using WebApplication2.Controllers
@model WebApplication2.Controllers.MyModel
@{
ViewBag.Title = "Home Page";
ViewBag.FleetType = new SelectList(
VehicleOwnerFleetTypeFactory.GetTypes().OrderBy(l => l.Type),
"Id",
"Type");
}
<div>
<h2>---------------------------</h2>
@Html.DropDownListFor(model => model.FleetType,
(SelectList)ViewBag.FleetType)
<h2>---------------------------</h2>
</div>
和
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyModel { FleetType = 2 });
}
}
public class MyModel
{
public int FleetType { get; set; }
}
public class VehicleOwnerFleetTypeFactory
{
public static FleetType[] GetTypes()
{
return new[]
{
new FleetType {Id = 1, Type = "Type 1"},
new FleetType {Id = 2, Type = "Type 2"},
new FleetType {Id = 3, Type = "Type 3"}
};
}
}
public class FleetType
{
public int Id { get; set; }
public string Type { get; set; }
}
}