【问题标题】:MVC Model loses bindingMVC 模型失去绑定
【发布时间】:2013-10-23 01:56:57
【问题描述】:

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

/彼得

【问题讨论】:

  • 这只是视图,底层逻辑在哪里?

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

您对 dropdownlistfor 的绑定不正确。

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

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

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

希望这会有所帮助...

【讨论】:

  • 正如您在我更新的帖子中看到的,列表中的项目实际上是 SelectListItems,所以我猜它们是按标准映射的。
【解决方案2】:

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

【讨论】:

  • 这正是你应该照顾它的方式。由于 Web 的无状态性,来自 MVVM/WPF 可能会有点挑战。提供视图(填充数据)后,如果您发布数据并且 ModelState 无效存在问题,则需要手动重新填充下拉列表,因为该信息不会随 POST 一起发回。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多