2017-01-23 52 views
-4

下面的HTML代码中发现Index.cshtml--如何提高HTML使用剃刀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辅助的HTML,如DropDownListForValidationMessageFor

+0

请改善你所要求的...,只需使用DropDownListFor。如果你问如何使用DropDownListFor,然后问... – Seabizkit

回答

0

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

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

我假设你的国家类有属性。 (Id和Name)

现在在您的视图中。您可以这样使用

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

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