1

如何在 SelectList 中显示所选 id (CountryId) 中的文本值(CountryName)?SelectList 包含在发送到详细信息视图模板的视图模型中。该字段当前显示 CountryID。我想要国名。

看法

<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 表达式?

4

2 回答 2

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>

感谢相关帖子。

于 2011-01-31T14:28:12.420 回答
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>
于 2013-07-31T19:10:41.517 回答