Select ENUM Tag Helper in ASP.NET Core MVC

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

I need some help with an ENUM dropdown using Tag Helper.

I found lots exemples binding a model to Selectlist and some using ENUM but all of them, about CREATE action, and Im facing problems with EDIT action.

MY MODEL

On my old project based on MVC5 I just used this on my View and it was enough.

DROPDOWN

I tried with difent ways and I coudnt set the dropdown with database item select on Edit action. I tried this way:

<div class="form-group">     <label asp-for="TipoLog" class="col-md-2 control-label"></label>     <div class="col-md-10">                       <select asp-for="TipoLog" class="form-control"></select>          <span asp-validation-for="TipoLog" class="text-danger"></span>      </div> </div> 

I also tried like that:

 <div class="form-group">      <label asp-for="TipoLog" class="col-md-2 control-label"></label>      <div class="col-md-10">            <select asp-for="TipoLog" asp-items="Html.GetEnumSelectList<TipoLog>()"></select>            <span asp-validation-for="TipoLog" class="text-danger"></span>       </div> </div> 

But it ran me to an compilation error:

I also tryed to bind a model a list to a ViewBag on my controller, this way:

CONTROLLER:

ViewBag.Log = new SelectList(lista, "Id", "Nome"); 

VIEW:

 <div class="form-group col-sm-2">       <label asp-for="TipoLogo" class="col-md-2 control-label"></label>       <select asp-for="TipoLogo" asp-items="ViewBag.Log" class="form-control"></select>        <span asp-validation-for="TipoLogo" class="text-danger"></span> </div> 

Its worked partially, the drop down listed the items, but not selecting the correct item from database. it show the first on the list as selected.

回答1:

You are forgetting to escape the C# code inside the HTML with "@"

Try:

<select asp-for="TipoLog" asp-items="Html.GetEnumSelectList<TipoLog>()"></select> 

Updated to remove @ before Html.Get....



回答2:

Finally I found the solution!

It doesn't seem obvious but that way I have no compilation erros. The answer I got from Ivan was not incorrect, but it was necessary to import the CRM.Model on the view like:

@using CRM.Model; 

So, my dropdown:

<select asp-for="TipoLog" asp-items="Html.GetEnumSelectList<ETipoLog>()" class="form-control"></select> 

You can see, Visual Studio told me it was unessessary, painting it in grey, but without that, i get compilation error. I hope I can help someone else.



回答3:

Try <select asp-for="TipoLog" asp-items="Html.GetEnumSelectList<ETipoLog>()"></select>



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!