0

我对 MVC 有疑问(这是新的,来自 WPF 中的 MVVM)。

我的 cshtml 文件中有一个组合框,可让用户从列表中选择一个国家/地区。但是,在我的模型中,当我尝试从列表中获取国家/地区时,该集合为空。

<div class="inputs">
    @Html.LabelFor(model => model.SelectedCountry)
    <div class="input-box">
        @Html.DropDownListFor(model => model.CountryID, Model.AvailableCountries)
    </div>
    @Html.ValidationMessageFor(model => model.SelectedCountry)
</div>

如您所见,我将选定的值绑定到 CountryID。在我的模型中,我使用这个 CountryID 从国家列表中获取名称,并将 SelectedCountry 字符串设置为用户选择的任何内容。

问题是当我尝试从模型中的列表中获取国家/地区时,列表为空。

我的模型中的国家列表:

public IList<SelectListItem> AvailableCountries 
{ 
    get
    {
        if (_availableCountries == null)
            _availableCountries = new List<SelectListItem>();
        return _availableCountries;
    }
    set
    {
        _availableCountries = value;
    }
}

以及我控制器中国家/地区列表的人口。

foreach (var c in _countryService.GetAllCountries())
{
    model.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() });
}

此外,正如您在 cshtml 中看到的,该值绑定到 CountryIID,该属性的代码为:

public int CountryID
{
    get
    {
        return _countryID;
    }
    set
    {
        if (_countryID != value)
        {
            _countryID = value;
            List<SelectListItem> _list = new List<SelectListItem>(AvailableCountries);
                SelectedCountry = _list.Find(x => x.Value == _countryID.ToString()).Text;
        }
    }
}

/彼得

4

2 回答 2

1

您对 dropdownlistfor 的绑定不正确。

您应该提供字段名称,其值将由 Razor 引擎绑定到下拉列表,因为您需要在下拉列表中提供要绑定的属性名称。试试这个

@Html.DropDownListFor(model => model.ActionId, new SelectList(@Model.AvailableCountries,"AccountID","AccountName"))

其中 AccountId,AccountName 是其中的属性字段,AvailableCountries其中 AccountName 值将显示在页面中,AccountId 将在选择时绑定。

希望这可以帮助...

于 2013-10-15T11:27:40.040 回答
0

通过照顾 CountryId 并将其翻译到我的控制器中解决了这个问题。然后,如果模型无效,只需重新填充 AvailableCountries 列表并将其发送回视图。

于 2013-10-16T07:44:09.797 回答