【问题标题】:How to select specific country from dropdown list in EF when page loads in asp.net mvc在asp.net mvc中加载页面时如何从EF的下拉列表中选择特定国家
【发布时间】:2019-06-14 12:29:48
【问题描述】:

我已使用 EF 将数据库中的数据填充到国家/地区的下拉列表中。我在下拉列表中有 100 多个国家/地区。

但我想在页面加载时选择一个特定国家/地区New Zealand

你能告诉我怎么做吗?

 private static List<SelectListItem> GetCountries()
        {
            AayuDBEntities db = new AayuDBEntities();
            List<SelectListItem> CountriesList = (from p in db.Countries.AsEnumerable()
                                               select new SelectListItem
                                               {
                                                   Text = p.Name,
                                                   Value = p.Country_Id.ToString()
                                               }).ToList();



            return CountriesList;
        }

.cshtml代码

 @Html.DropDownListFor(x => Model.Country, Model.Countries, htmlAttributes: new { @class = "form-control"})

【问题讨论】:

  • 嗨。你试过什么了 ?请在发布问题之前"read this"

标签: c# asp.net-mvc entity-framework


【解决方案1】:

关注这个

@Html.DropDownListFor(
m => m.CountryId, // Specifies where to store selected country Id
                  // It needs to be null for the default selection to work!

new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
               "Id",   // Use Country.Id as a data source for the values of dropdown items
               "Name", // Use Country.Name as a data source for the text of dropdown items
               13 // Specifies Australia (which has ID of 13) as the element selected by default
               ),

【讨论】:

  • 上面说,还有cmets,需要什么指南?
  • 我使用不同的方式来填充下拉列表中的数据,而您使用了不同的方式。
【解决方案2】:
 @Html.DropDownListFor(model => model.SlectedValue, Model.CountryList, "Please select", new { id = "ddlCity" })

这样做,可能会有所帮助。 :)

【讨论】:

  • 我不想使用Please select。我想在页面加载时选择国家新西兰。
  • OK@user11642353
猜你喜欢
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 2019-04-09
  • 2021-11-18
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多