Asp.net-Mvc

在 ASP.NET Core MVC 中選擇 ENUM Tag Helper

  • January 23, 2022

我需要一些關於使用 Tag Helper 的 ENUM 下拉列表的幫​​助。

我發現了很多將模型綁定到 Selectlist 的範例,還有一些使用 ENUM,但所有這些範例都與 CREATE 操作有關,並且我面臨 EDIT 操作的問題。

我的模特

public class ProspectLog
   {
       public int Id { get; set; }
       public int IdProspect { get; set; }
       public int IdEmpresa { get; set; }
       public DateTime Criado { get; set; }
       public string Usuario { get; set; }
       public string Descricao { get; set; }

       public ETipoLog TipoLog { get; set; }

       public enum ETipoLog
       {
           [Display(Name = "CADASTRO")]
           Cadastro = 0,
           [Display(Name = "CONTATO")]
           Contato = 1,
           [Display(Name = @"TROCA ETAPA")]
           Troca = 2,
           [Display(Name = @"QUALIFICAÇÃO")]
           Qualifica = 3,
           [Display(Name = @"EDIÇÃO")]
           Edicao = 4
       }
   }

在我基於 MVC5 的舊項目中,我只是在 View 上使用了它,這就足夠了。

落下

<div class="form-group col-sm-6">
  <label style="font-weight: bolder" for="txtSituacao">Situação</label>
  @Html.EnumDropDownListFor(model => model.Situacao, htmlAttributes: new { @class = "form-control" })
  @Html.ValidationMessageFor(model => model.Situacao, "", new { @class = "text-danger" })
</div>

我嘗試了不同的方法,並且在編輯操作上使用數據庫項目選擇來設置下拉菜單。我試過這樣:

<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>

我也試過這樣:

<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>

但這讓我遇到了編譯錯誤: 在此處輸入圖像描述

我還嘗試通過這種方式將模型列表綁定到控制器上的 ViewBag:

控制器:

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

看法:

<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>

它部分工作,下拉列表列出了項目,但沒有從數據庫中選擇正確的項目。它顯示列表中的第一個被選中。

最後我找到了解決方案!

這似乎並不明顯,但這樣我就沒有編譯錯誤!!!我從 Ivan 那裡得到的答案並不正確,但有必要CRM.Model在視圖上導入,例如:

@using CRM.Model;

所以,我的下拉列表:

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

在此處輸入圖像描述

你可以看到,Visual Studio 告訴我這是不必要的,將它塗成灰色,但沒有它,我得到編譯錯誤。我希望我能幫助別人。

您忘記使用“@”轉義 HTML 中的 C# 程式碼

嘗試:

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

更新為在 Html.Get…. 之前刪除 @

引用自:https://stackoverflow.com/questions/44761915