我有模型值,想显示在@Html.DropDownList 或@Html.DropDownListFor
I have model values and wanted to display in @Html.DropDownList or @Html.DropDownListFor
我是 razor 视图页面的新手。
我有一个模型,我在其中获取列表值并希望使用 @Html.DropDownListFor/@Html.DropDownList 在视图中显示它,请有人帮我提供代码片段。
我有模型的照片(附上)。
由于我对 Razor 不太了解,所以我最终得到了 html select 标签并使用 jquery 来获取数据,但问题是,我需要到 post 更新模型到 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 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>
希望对您有所帮助
我是 razor 视图页面的新手。 我有一个模型,我在其中获取列表值并希望使用 @Html.DropDownListFor/@Html.DropDownList 在视图中显示它,请有人帮我提供代码片段。 我有模型的照片(附上)。
由于我对 Razor 不太了解,所以我最终得到了 html select 标签并使用 jquery 来获取数据,但问题是,我需要到 post 更新模型到 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 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>
希望对您有所帮助