DropDownList的行为不符合预期

时间:2014-07-24 19:12:53

标签: c# asp.net-mvc html.dropdownlistfor dropdownlistfor

我的DropDownListFors遇到了麻烦,我希望你能帮助我。我猜这是你要么知道的事情之一,要么你不知道。

问题是我的数据库中有一个国家/地区表,其中包含国家/地区列表。我从下拉列表中想要的行为是在我的地址表中创建一个外键引用,指向下拉列表中选择的县。我得到的行为是我的地址表中的外键指向国家中一个完全不需要的新条目。

任何人都可以解释如何做到这一点?我不确定你们想要看哪些代码,所以如果你能提供帮助,请告诉我。

===更多信息===

好的,我有一个像这样的视图模型类:

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中结束。

帮助!我一直在摆弄这个并整天重构!

期待您的回复。

中号

1 个答案:

答案 0 :(得分:1)

有多种方法可以做到这一点。例如,您可以加载AddressViewModel中的国家/地区列表。

即。

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 );
    }
相关问题