当页面在asp.net mvc

时间:2019-06-14 12:29:48

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

我已经使用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"})

2 个答案:

答案 0 :(得分:0)

关注

@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
               ),

答案 1 :(得分:0)

 @Html.DropDownListFor(model => model.SlectedValue, Model.CountryList, "Please select", new { id = "ddlCity" })

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