2017-01-23 50 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添加額外的必需類。