访问控制器上的枚举值

时间:2014-04-04 06:17:48

标签: c# asp.net-mvc-4 if-statement enums

我有一个字段状态的枚举

  public status? Status { get; set; }

和班级为

 public enum status
    {
        Incomplete = 0,
        InReview,
        Live,
        Rejected,
        Suspended,
        Scheduled,
        Delisted
    }

在我的模型中,我使用

填充我的视图
var listStatus = new List<SelectListItem>();
listStatus.Add(new SelectListItem { Selected = true, Text = "Incomplete", Value = "Incomplete" });
listStatus.Add(new SelectListItem { Selected = false, Text = "Ready for Review", Value = "InReview" });

            model.Status = listStatus;
     //above are in controller to initialise z model's list
    [Display(Name = "Status")]
    public IEnumerable<SelectListItem> Status { get; set; }
    public status selectedStatus { get; set; }

在视图中

 @Html.DropDownListFor(m => m.selectedStatus, Model.Status)

问题?

在提交表单时,我想验证用户的选择以继续 我的意思是我想做一些事情

if(selectedStatus = "Incomplete")
{
//my codes hre
}

问题:

如何在控制器中访问与用户选择匹配的枚举值?

2 个答案:

答案 0 :(得分:0)

只需发布适合未来访问者的解决方案。

            var  chosenStatus = model.selectedStatus;

            if (chosenStatus == status.Incomplete)
            {

            }

答案 1 :(得分:0)

试试这个。

在获取行动中:

var statuses = from Status s in Enum.GetValues(typeof(Status)) 
               select new { Id = (int)s, Name = s.ToString() };

ViewBag.Statuses = new SelectList(statuses, "Id", "Name", (int)Status.Live /*selected*/ );

在视图中:

@Html.DropDownListFor(model => model.StatusId, ViewBag.Statuses as IEnumerable<SelectListItem>, "Select a status" )

在Post post中:

if(model.StatusId == (int)Status.InReview)
{
   // do your work..
}