如何在SelectList中显示所选id(CountryId)的文本值(CountryName)? SelectList包含在发送到Details视图模板的视图模型中。该字段当前显示CountryID。我想要CountryName。
视图
<div class="display-field">@Model.Dinner.CountryID</div>
控制器
public ActionResult Details(int id)
{
Dinner dinner = dinnerRepository.GetDinner(id);
DinnerFormViewModel model = new DinnerFormViewModel(dinner);
if (dinner == null)
return View("NotFound");
else
return View("Details", model);
}
视图模型
public class DinnerFormViewModel
{
public Dinner Dinner { get; private set; }
public SelectList CountriesList { get; private set; }
public DinnerFormViewModel(Dinner dinner)
{
Dinner = dinner;
var items = new List<Country>() {
new Country() {
CountryID = 1,
CountryName = "England"
},
new Country() {
CountryID = 2,
CountryName = "Ireland"
},
new Country() {
CountryID = 3,
CountryName = "Scotland"
},
new Country() {
CountryID = 3,
CountryName = "Wales"
}
};
CountriesList = new SelectList(items, "CountryID", "CountryName", 2);
}
}
同样,这只是在标签中显示CountryName值。不想编辑它或任何东西。 LINQ表达式?
答案 0 :(得分:2)
这很棒
<div class="display-label">Country</div>
<div class="display-field">@Html.Encode(Model.CountriesList.SingleOrDefault(c => int.Parse(c.Value) == Model.Dinner.CountryID).Text)</div>
感谢related帖子。
答案 1 :(得分:1)
我会创建一个新类来帮助查找。在我的示例代码中,类是“BusinessResources”在该类中,我将为每个查找创建一个方法,如下面描述的国家/地区。字典非常适合您想要完成的任务。
public static Dictionary<string, string> GetCountryList()
{
Dictionary<string, string> country = new Dictionary<string, string>();
Capture2Entities db = new Capture2Entities();
country = db.CountryLists.Where(x => x.IsDisabled == false)
.OrderBy(x => x.CountryName)
.Select(x => new { x.ID_Country, x.CountryName })
.ToDictionary(key => key.ID_Country.ToString(), val => val.CountryName);
return country;
}
视图看起来像这样
<div class="display-label">@Html.LabelFor(model => model.ID_Country)</div>
<div class="display-field">@Html.DropDownListFor(model => model.ID_Country, new SelectList(BusinessResources.GetCountryList(),"Key","Value"))</div>