将模型显示到非剃刀下拉列表

时间:2016-11-23 10:05:32

标签: c# asp.net-mvc razor html.dropdownlistfor

是否可以在cshtml中显示普通html下拉列表的模型 或者我应该单独使用ajax?什么是最好的选择?



            @foreach (var item in Model)
            {
                <tr>            
                    <td>@Html.DisplayFor(modelItem => item.ReservationId)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationStartDate)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationEndDate)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationAdult)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationChildren)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationRoomDesc)</td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationRoomType)</td>
                    <td><select id="hotelroom" name="cs3" class="cs3 form-control input-small"></select></td>
                    <td>@Html.DisplayFor(modelItem => item.ReservationRoomStatus)</td>      
                    <td><input type="button" id="editTable"></td>
                </tr>
            }
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以使用Razor像任何其他标记一样呈现<option>标记。

我假设您的模型中有潜在选项IEnumerable<SelectListItem> AvailableHotelRoomOptions

<td>
    <select id="hotelroom" name="cs3" class="cs3 form-control input-small"> 
    @foreach(var selectListItem in Model.AvailableHotelRoomOptions) {
        @{ string selectedAttr = selectListItem.Selected ? "selected = \"selected\"" : string.Empty; }
        <option value="@selectListItem.Value" @selectedAttr>
            @selectListItem.Text
        </option>
    }
    </select>
</td>

PS:确保<select>的Id和Name属性与MVC ModelBinder所期望的命名约定相匹配,以便它可以绑定回来!

答案 1 :(得分:0)

您可以创建如下的下拉列表:

@Html.DropDownListFor(
    modelItem => modelItem.AvailableHotelRoomOptions, 
    new SelectList(Model.AvailableHotelRoomOptions.Select(@r => @r.OptionName)),
    new { @id = "hotelroom", @class = "cs3 form-control input-small" }
)

或者像这样:

@Html.DropDownListFor(
    modelItem => modelItem.AvailableHotelRoomOptions, 
    new SelectList(Model.AvailableHotelRoomOptions, "OptionId", "OptionValue"),
    new { @id = "hotelroom", @class = "cs3 form-control input-small" }
)