亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MVC 5-如何在DropDownListFor HTML助手中設置“selectedValue”

MVC 5-如何在DropDownListFor HTML助手中設置“selectedValue”

千巷貓影 2019-06-20 15:54:24
MVC 5-如何在DropDownListFor HTML助手中設置“selectedValue”問題是:如何在DropDownListFor HTML助手中設置selectedValue?嘗試了大多數其他的解決方案,但都沒有奏效,這就是為什么我要提出一個新的問題。這些都沒有幫助:@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { @class = "form-control" })//Not working with or without [email protected](m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { @class = "form-control" })@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { @class = "form-control" })@Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { @class = "form-control" })如果可能的話,我希望避免手動創建SelectListItems或ViewModel。
查看完整描述

3 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

public static class EnumHelper{
    public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue)
    {  
        return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
    }}

在你看來:

@Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role),  
new { htmlAttributes = new { @class = "padding_right" } })@Html.ValidationMessageFor(model => model.Role, "", new { @class = "text-danger" })

而不是EnumToList,使用任何其他列表并選擇列表類型屬性的鍵和值


查看完整回答
反對 回復 2019-06-20
  • 3 回答
  • 0 關注
  • 739 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號