[英]How to bind key value pair to dropdown in MVC4 Razor
我有国家表“ tblCountry”,其中有2列国家名称,国家ID,我想显示国家名称,但将国家ID存储在其余表中。 请告诉我从创建模型到查看模型的方法,我正在使用数据库优先方法。
public partial class tblRFATCountry
{
public long CountryID { get; set; }
public string Country { get; set; }
}
这是我尝试添加字典的模型。
public partial class tblRFATCountry
{
public long CountryID { get; set; }
public string Country { get; set; }
public dictionary<string, long> countryDic = new dictionary<string, long>();
}
我想做这样的事情,以便我可以显示名称但可以存储价值。 请建议
下拉列表可以如下实现
@Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.Countries, "CountryID", "Country"), "Please select a country")
然后,ViewModel需要以下属性
public long SelectedCountryId {get; set;}
public List<tblRFATCountry> Countries {get; set;}
您需要执行以下操作:
@{
Dictionary<long, string> dictionaryCountry = new Dictionary<long, string>()
{
{1, "Item1"},
{2, "Item2"},
{3, "Item3"},
{4, "Item4"},
};
SelectList countryList= new SelectList(
dictionaryCountry.Select(x => new { Value = x.Key, Text = x.Value }),
"Value",
"Text"
);
}
@Html.DropDownList("DDLCounry", countryList)
借助实用程序类,您可以执行以下操作
C#实用程序类
using System.Collections.Generic;using System.Web.Mvc;
namespace YourNameSpace.Domain.Utilities
{
public static class DropDownList<T>
{
public static SelectList LoadItems(IList<T> collection, string value, string text)
{
return new SelectList(collection, value, text);
}
}
}
控制者
ViewBag.CountryList = Domain.Utilities.DropDownList<tblRFATCountry>.LoadItems(YourRepository.Countries.ToList(),
"CityID", "CityName");
视图
@Html.DropDownListFor(model => model.CountryID, (IEnumerable<SelectListItem>)ViewBag.CountryList, "--Select--", new { @class = "select" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.