【问题标题】:How to improve the HTML to use Razor HTML Helpers如何改进 HTML 以使用 Razor HTML Helpers
【发布时间】:2017-06-07 12:45:07
【问题描述】:

在Index.cshtml中可以找到以下HTML代码--

<select data-val="true" data-val-required="Please choose your country "
                    id="Country" name="Country" class="form-control" style="width: 200px;" >
    <option value="">-- Select Country --</option >
    @foreach (var country in (List<Country>)ViewBag.AvailableCountries )
    {
      <option value="@country.Id">@country.Name</option >
    }
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="Country "
data-valmsg-replace="true"></span>

请改进 HTML 以使用 Razor HTML Helpers,例如 DropDownListForValidationMessageFor.

【问题讨论】:

  • 请改进您的要求...,只需使用 DropDownListFor。如果你问如何使用 DropDownListFor,那么问那个...

标签: c# html razor


【解决方案1】:

将此代码添加到您的操作中。

var countries =new List<Country>(); //assign list of country here.
ViewBag.AvailableCountries =  countries.Select(x => new SelectListItem
                               {
                                   Value = x.Id,
                                   Text = x.Name
                               }).ToList();

我假设你的国家级有财产。 (身份证和姓名)

现在在你看来。你可以这样使用

 @Html.DropDownListFor(x => x.County, ViewBag.AvailableCountries as IEnumerable<SelectListItem>, new { @class = "form-control" })

在模型类的 Country 属性上添加必需属性。所以你不需要为选择添加额外的必需类。

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2013-08-05
    • 2015-07-02
    • 2011-10-17
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多