MVC 模型失去绑定

本文关键字:绑定 失去 模型 MVC | 更新日期: 2023-09-27 18:35:37

我对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>

如您所见,我将所选值绑定到国家/地区 ID。在我的模型中,我使用此 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;
        }
    }
}

/彼得

MVC 模型失去绑定

下拉列表的绑定不正确。

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

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

其中,帐户 ID,帐户名称是 AvailableCountries 中的属性字段,其中帐户名称值将显示在页面中,帐户 ID 将在选择时绑定。

希望这有帮助...

通过处理 CountryId 并在我的控制器中翻译它来解决此问题。然后,如果模型无效,则只需重新填充"可用国家/地区"列表,并将其发送回视图。