我有一个这样的自定义视图模型:
namespace MyCustomNamespace.Models
{
public class CustomViewModel
{
public CustomViewModel()
{
FirstViewModel = new FirstModel ();
SecondViewModel = new SecondModel ();
}
public FirstModel FirstViewModel { get; set; }
public SecondModel SecondViewModel { get; set; }
}
}
namespace MyCustomNamespace.Models
{
public class FirstModel
{
public string id { get; set; }
public string text { get; set; }
public IEnumerable<SelectListItem> Items
{
(...)
}
(...)
}
}
SecondModel 类似于 FirstModel。
在我看来,我确实使用剃须刀:
@model MyCustomNamespace.Models.CustomViewModel
(...)
@Html.DropDownListFor(m => m.FirstViewModel.Id, Model.FirstViewModel.Items)
(...)
我用模型填充下拉列表。
我想知道上面显示的下拉列表中当前选定的元素是哪个,但我不知道如何....也许通过模型?但如何?
更新: 这是我真正的模型类型,上面是我在做什么的一个例子。在这种情况下,FirstModel 将是 ComponentTypeModel:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System;
using Resources;
namespace MyCustomNamespace.Models
{
public class ComponentTypeModel
{
private readonly List<ComponentType> componentTypes;
public ComponentTypeModel()
{
using (ConfigContext dbContext = new ConfigContext())
{
try
{
componentTypes = dbContext.ComponentTypes.ToList();
}
catch (Exception ex)
{
//EventLogger.LogException(ex);
}
}
}
[Display(Name = "Component Type")]
public int SelectedCompTypeId { get; set; }
public IEnumerable<SelectListItem> CompTypeItems
{
get
{
var allCompTypes = componentTypes.Select(f => new SelectListItem
{
Value = f.ComponentTypeId.ToString(),
Text = f.Name
});
return DefaultCompTypeItem.Concat(allCompTypes);
}
}
public IEnumerable<SelectListItem> DefaultCompTypeItem
{
get
{
return Enumerable.Repeat(new SelectListItem
{
Value = "-1",
Text = "Select a component type"
},
count: 1);
}
}
}
}