我有国家表“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>();
}
我想做类似的事情,以便我可以显示名称但存储价值。请建议
答案 0 :(得分:4)
下拉列表可以按如下方式实现
@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;}
答案 1 :(得分:3)
你需要做类似的事情:
@{
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)
答案 2 :(得分:1)
在实用程序类的帮助下,您可以执行类似这样的操作
C#Utility Class
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" })