簡體   English   中英

如何獲得枚舉值ASP.NET MVC

[英]How to get an enum value ASP.NET MVC

我有一個ProjectsModel作為viewmodel:

public IEnumerable<TheProjects> OurProjects { get; set; }

public class TheProjects
{
    public int Id { get; set; }

    public string ProjectName { get; set; }
    public short PhaseCount { get; set; }
    public string ProjectOwner { get; set; }
    public byte Priority { get; set; }
}

我將Project作為模型:

public enum PriorityForProject
{
    Acil = 0,
    Normal = 1,
    Düsük = 2
}

namespace JobTracking.Models
{
    public class Project
    {
        public int Id { get; set; }
        public string ProjectName { get; set; }
        public int ProjectNo { get; set; }
        public string ProjectType { get; set; }
        public string ProjectOwner { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
        public string ProjectManager { get; set; }
        public string Team { get; set; }
        public string ProjectDescription { get; set; }
        public PriorityForProject Priority { get; set; }
        public string Costs { get; set; }
        public string CashExpenditures { get; set; }
        public short Sira { get; set; }
    }
}

如您所見,我的project.cs中有枚舉,這是我的控制器:

public ActionResult Index(int S = 1)
{
    var itemsPerPage = 100;
    var model = new ProjectsModel
    {
        ItemsPerPage = itemsPerPage,
        Page = S,
        TotalItems = Db.MyProjects.Count(),
        OurProjects = Db.MyProjects.OrderByDescending(o => o.Sira).Skip((S - 1) * itemsPerPage).Take(itemsPerPage)
        .Select(s => new ProjectsModel.TheProjects
        {
            Id = s.Id,
            ProjectName = s.ProjectName,
            PhaseCount = (short)Db.MyPhases.Where(p => p.Project.Id == s.Id).Count(),
            ProjectOwner=s.ProjectOwner,
            Priority = (byte)s.Priority
        })
    };
    return View(model);
}

我正在嘗試獲取PriorityForProject方法的值。 如您所見,從控制器中,我可以獲取返回數字的字節類型。 我如何達到它的價值?

剛投:

TheProjects x = ...;
PriorityForProject priority = (PriorityForProject) x.Priority;

(不過,我強烈建議您重命名TheProjects類型-這是一個非常笨拙的名稱,...)

您必須強制轉換為propertyforproject類型(PriorityForProject)

如果您不想使用值,可以在模型中聲明PropertyForProject屬性。

public class TheProjects
    {
        public int Id { get; set; }
        public string ProjectName { get; set; }
        public short PhaseCount { get; set; }
        public string ProjectOwner { get; set; }
        public byte PriorityValue { get; set; } /* check if you really need this */
        public PriorityForProject Priority { get; set; }

    }

我假設枚舉位於您的應用程序的核心級別,因此引用一定不會有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM