【问题标题】:I have model values and wanted to display in @Html.DropDownList or @Html.DropDownListFor我有模型值并希望在 @Html.DropDownList 或 @Html.DropDownListFor 中显示
【发布时间】:2019-05-09 20:56:48
【问题描述】:

我是剃刀视图页面的新手。 我有一个模型,我可以在其中获取列表值并希望在视图上显示它,使用 @Html.DropDownListFor/@Html.DropDownList,有人请帮我编写代码 sn-p。 我有模特的照片(附上)。

由于我对 Razor 没有太多了解,我最终得到了 html select 标签并使用 jquery 获取数据,但问题是,我需要将更新的模型发布到 mvc 控制器。

public class CountryViewModel
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
        public string CountryCodeISO3 { get; set; }
        public string CountryCodeISO2 { get; set; }
    }

【问题讨论】:

  • public IEnumerable 国家 { get;放;是否需要 List

标签: asp.net-mvc razor-pages


【解决方案1】:

你可以做这样的事情(还没有测试过)

在模型中添加属性

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

获取属性值

List<SelectListItem> Countries = new List<SelectListItem>();

    foreach (var item in _db.Countries)
                    {
                        Countries.Add(new SelectListItem
                        {
                            Text = item.CountryName,
                            Value = item.Id.ToString()
                        });
                    }

在你看来

<select class="form-control" id="countryId">
        <option selected="selected" value="-1"></option>
        @foreach (var item in Model.Countries)
        {
            <option value="@item.Value">@item.Text</option>
        }
    </select>

希望对你有帮助

【讨论】:

  • 感谢您的回复。我考虑过您提供的解决方案,但问题是我需要 countryViewModel 的 3 个属性,以实现我的业务逻辑,如果我使用 SelectListItem 我只能使用 2 个属性。
猜你喜欢
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
相关资源
最近更新 更多