2

我在我的應用程序中使用ADO.NET實體框架將我的數據庫映射到模型中。我設置我的ViewModel註冊類似以下內容:正確設置MVC中的DropDownListFor 5

public class UserRegistrationViewModel 
    { 
     public string FirstName { get; set; } 

     public string LastName { get; set; } 
     public string Email { get; set; } 
     public string Password { get; set; } 
     public string PasswordConfirm { get; set; } 
     public SelectList Countries { get; set; } 

    } 

這裏的特定部分是我要填寫我的下拉列表中從我的DbContext國家,看起來像這樣:

Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList(); 

由於你可以看到國家名單現在,在我看來,我想使用HTML輔助類這樣的設立一個下拉列表:

@Html.DropDownListFor(model => model.Countries); 

這就是我是如何映射到我的模型視圖:

@model WebApplication2.ViewModels.UserRegistrationViewModel 

如何正確設置下拉列表(即:選擇列表),以便我可以顯示數據庫中的數據?

回答

1

在你的視圖模型添加一個屬性來保存所選國家的ID:

public class UserRegistrationViewModel 
{ 
    // 
    public int SelectedCountryId { get; set; } 
    public SelectList Countries { get; set; } 

} 

我要去當時猜測設置國家屬性,你正在做的事情是這樣的:

var countries=Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList(); 
//... 
viemodel.Countries=new SelectList(countries, "CountryId", "CountryName"); 

然後在您的視圖中可以執行以下操作:

@Html.DropDownListFor(model => model.SelectedCountryId, Model.Countries) 
+0

嘿,當我嘗試使用此方法時,它顯示出此錯誤:'System.Data.Entity.DynamicProxies.Countries_72FA95A5B14211F073C8C11B1E3587265F1CE9063C9540E555C16AC7031F4887'不包含屬性名稱爲「Id」。 – User987

+0

你的國家實體中的PK是什麼? – octavioccl

+0

CountryId現在 – User987

2

您需要兩個屬性:一個持有所選擇的價值和一個保存您的選擇列表選項:

public string Country { get; set; } 

public IEnumerable<SelectListItem> CountryOptions { get; set; } 

然後,在你的看法:

@Html.DropDownListFor(m => m.Country, Model.CountryOptions) 

你並不需要一個實際SelectList。事實上,如果你不這樣做,這是最好的。剃刀會自動創建一個SelectList並選擇適當的值。

+0

以及如何填入實際的R中的國家選項來自我的數據庫的生態? :DI不能使用我簡單地將所有記錄轉換爲列表的方法lol – User987

+0

您只需將它們選擇到一個「SelectListItem」集合中,即db.Countries.Select(m => new SelectListItem {Value = m .Iso2,Text = m.Name})'。 (顯然,你可以將屬性名稱更改爲您的'Country'實體上的實際名稱。) –