在枚举属性中检查null

时间:2016-11-01 04:05:53

标签: c# asp.net enums

我有一个枚举属性,我用它来填充下拉列表作为我的表单的一部分,如下所示:

 public class MyModel
{
    [Required]
    [DisplayName("Type of Enum")]
    public EnumType? Type { get; set; }
}

public enum EnumType
{
    option1 = 1,
    option2 = 2,
    option3 = 3,
    option4 = 4
}

表单提交给另一个控制器,我试图在枚举类型中检查null:

 public class ResultController : Controller
{
    // GET: Result
    [AllowAnonymous]
    public ActionResult Index(MyModel model)
    {
        if(!Enum.IsDefined(typeof(MyEnum), model.EnumType))
        {
            return RedirectToAction("Index", "Home");
        }           
        return View();
    }
}

当我尝试使用..../result?Type=5 RedirectToAction时,我尝试..../result?Type=时会得到ArgumentNullException

注意:在枚举中添加None=0对我来说不是一个选项,我不希望在下拉列表中显示任何内容。

如何检查控制器中的null?在这方面有最好的做法吗?

2 个答案:

答案 0 :(得分:3)

Firebase中使用该值之前,请先明确检查该值是否为null

IsDefined()

较短的版本是使用null-coalesce operatorpublic ActionResult Index(MyModel model) { if(!model.EnumType.HasValue) { return RedirectToAction("Index", "Home"); } if(!Enum.IsDefined(typeof(MyEnum), model.EnumType)) { return RedirectToAction("Index", "Home"); } return View(); } 的调用中使用0代替null

IsDefined()

答案 1 :(得分:2)

首先,根据您的模型,Type属性是必需的。

public class MyModel
{
    [Required]
    [DisplayName("Type of Enum")]
    public EnumType? Type { get; set; }
}

其次,您需要检查枚举值是否已在EnumType声明中明确定义,然后您不需要在操作中调用Enum.isDefined方法。只需使用数据注释属性Type装饰您的EnumDataType(typeof(EnumType))属性即可完成该任务。所以你的模型看起来像这样:

public class MyModel
{
    [Required]
    [EnumDataType(typeof(EnumType))]
    [DisplayName("Type of Enum")]
    public EnumType? Type { get; set; }
}

最后,在您的控制器操作中,只需清理它,看起来就是这样:

// GET: Result
[AllowAnonymous]
public ActionResult Index(MyModel model)
{
    // IsValid will check that the Type property is setted and will exectue 
    // the data annotation attribute EnumDataType which check that 
    // the enum value is correct.
    if (!ModelState.IsValid) 
    {
        return RedirectToAction("Index", "Home");
    }
    return View();
}
相关问题