當前選擇我有這樣的自定義視圖模式:試圖瞭解哪些因素在@ Html.DropDownListFor
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);
}
}
}
}
它應該是'm.FirstViewModel.Id',你可以在客戶端訪問'$('#your-ddl-id')。val()' –