无法更新实体中的枚举属性

问题描述 投票:0回答:1

我在更新问题实体中的枚举属性时遇到问题。以下是我的代码和错误消息的相关部分:

标签助手“选项”在元素的属性中不得包含 C# 报关区。

问题.cs:

using quiz.Entities;
using System.ComponentModel;

public class Question
{
    public Guid Id { get; set; }

    [DisplayName("Question's Text")]
    public string QuestionText { get; set; }

    public enum DifficultyLevel
    {
        Easy,
        Medium,
        Hard
    }

    [DisplayName("Zorluk Derecesi")]
    public DifficultyLevel Difficulty { get; set; }

    [DisplayName("Şık A")]
    public string AnswerA { get; set; }

    [DisplayName("Şık B")]
    public string AnswerB { get; set; }

    [DisplayName("Şık C")]
    public string AnswerC { get; set; }

    [DisplayName("Şık D")]
    public string AnswerD { get; set; }

    [DisplayName("Doğru Şık")]
    public char CorrectAnswer { get; set; }

    [DisplayName("Movie Name (MovieId)")]
    public Guid MovieId { get; set; }

    public virtual Movie? Movie { get; set; }
}

编辑.cshtml:

<div class="form-group mb-4">
 <label asp-for="Difficulty" class="form-label font-weight-bold">Zorluk Derecesi</label>
 <select asp-for="Difficulty" class="form-control bg-secondary text-light border-0 shadow-sm">
     <option value="">Seçiniz</option>
     @foreach (var level in Enum.GetValues(typeof(Question.DifficultyLevel)))
     {
         <option value="@level.ToString()" @(Model.Difficulty == level ? "selected" : "")>@level</option>
     }
 </select>
 <span asp-validation-for="Difficulty" class="text-danger"></span>
c# .net asp.net-mvc
1个回答
0
投票

发生错误的原因是我在尝试在 Razor 视图的下拉列表中显示枚举值时使用了不正确的转换。由于 Enum.GetValues 不能直接用作数组,因此需要使用 Cast() 将其转换为 DifficultyLevel。 Razor 无法理解不正确的表达式,从而导致错误。

Edit.cshtml 中,我将执行 Enum 操作的表单替换为以下形式:

 <div class="form-group mb-4">
      <label asp-for="Difficulty" class="form-label font-weight-bold">Zorluk Derecesi</label>
      <select asp-for="Difficulty" class="form-control bg-secondary text-light border-0 shadow-sm">
          <option value="">Seçiniz</option>
          @foreach (var level in Enum.GetValues(typeof(Question.DifficultyLevel)).Cast<Question.DifficultyLevel>())
          {
              <option value="@level">@level</option>
          }
      </select>
      <span asp-validation-for="Difficulty" class="text-danger"></span>
  </div>
© www.soinside.com 2019 - 2024. All rights reserved.