2014-07-24 119 views
2

我遇到了我希望你能幫助我的DropDownListFors問題。我猜這是你知道或不知道的事情之一。DropDownList不像預期的那樣運行

問題是我在我的數據庫中有一個Countries表,裏面有一個國家列表。我想從我的下拉菜單中選擇的行爲是在地址表中創建一個外鍵引用,指向下拉列表中選定的縣。我得到的行爲是我的Address表中的外鍵指向Country中的一個新條目,這是完全不需要的。

任何人都可以解釋如何做到這一點?我不確定你們想看到什麼代碼,請讓我知道你是否可以提供幫助。

===更多信息===

好吧,我有一個視圖模型類是這樣的:

public class CountryViewModel 
{ 
    public int CountryId { get; set; } 
    public string Name { get; set; } 
} 

在我看來,我有一個下拉列表如下:

@Html.DropDownListFor(m => m.LegalEntity.Address.Country.CountryId, 
    new SelectList(Model.LegalEntity.Address.Country, 
     "CountryId", "Name", Model.LegalEntity.Address.Country.CountryId), 
new { @class = "form-control" })    

請注意,這目前的第二行目前沒有工作:我不知道如何讓整個國家的列表進入此。

我的法律實體視圖模型看起來是這樣的:

public class LegalEntityViewModel 
{ 
    [Key] 
    public int LegalEntityID { get; set; } 
    public virtual AddressViewModel Address { get; set; } 
    public virtual TechnicalContactViewModel TechnicalContact { get; set; } 
} 

和我的地址視圖模型看起來是這樣的:

public class AddressViewModel 
{ 
    [Key] 
    public int AddressID { get; set; } 
    ... 
    [Display(Name = "Country")] 
    public virtual CountryViewModel Country { get; set; } 
} 

我想的行爲是對所有國家來填充降向下和選定的國家在我的LegalEntityViewModel.AddressViewModel.CountryViewModel結束。

幫助!我一直在擺弄這個和重構整天!

期待您的回覆。

M

+0

你將不得不放棄一些更多的信息/後的代碼和/或數據庫結構。事實上,這個問題很難理解。 –

+0

在模型(理想情況下)或ViewBag屬性中以及模型中選定的國家/地區中是否有國家/地區屬性?看到View的代碼在這裏會有很大的幫助。 – barrick

回答

1

有多種方法可以做到這一點。例如,您可以加載AddressViewModel中的國家/地區列表。

I.e.

public class AddressViewModel 
{ 

    [Display(Name = "Country")] 
    public int SelectedCountryId { get; set; } 

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

然後在您的視圖做

@Html.DropDownListFor(m => m.SelectedCountryId , new SelectList(Model.Countries , "Value", "Text")) 

你也可以加載你的JavaScript的國家名單。

$(document).ready(function() { 
    $.ajax({ 
     type: 'POST', 
     url: '@Url.Action("GetCountries")', <--This will be a method in your controller that brings back the Countries, 
     success: function (results) { 
     var options = $('#SelectedCountryId'); 
     $.each(results, function() { 
      options.append($('<option />').val(this.CountryId).text(this.CountryName)); 
     }); 
    } 
    }); 

    public class CountryViewModel 
    { 
     public int CountryId {get;set;} 
     public int CountryName {get;set; 
    } 

在你的控制器

[HttpPost] 
    public JsonResult GetCountries() 
    { 
     var countries = //some method to get the countries for a database or something 
     var countriesList = countries .Select(x => new CountryViewModel { CountryId = x.CountryId, CountryName = x.CountryName }).ToList(); 
     return this.Json(countriesList); 
    } 
+0

這就是我最初的工作,但它沒有正確的綁定。問題在於國家實體代表國家,數據庫中相應的表已經預填。 – serlingpa

+0

下拉列表有2個屬性。某種標識(國家代碼,數字,獨特的東西)和文本值。在下拉列表中選擇一個項目可以返回id或文本,但通常是Id。我認爲你的問題可能是Razor代碼生成不夠聰明,無法弄清楚如何獲取選定的值並將其轉換爲CountryViewModel。您可能需要在控制器中處理該問題,儘管可能以其他方式進行處理。我不確定如何做到這一點。 – cgotberg

相關問題