简体   繁体   English

检查枚举属性是否为空

[英]Check for null in enum property

I've got an enum property that I'm using to populate a dropdown as part of my form that looks like this: 我有一个枚举属性,用于在我的表单中填充一个下拉列表,如下所示:

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

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

The form submits to another controller, where I'm trying to check for null in the enum type: 表单提交给另一个控制器,在这里我试图检查枚举类型中的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();
    }
}

When I try ..../result?Type=5 RedirectToAction works, but when I try ..../result?Type= I get ArgumentNullException . 当我尝试..../result?Type=5 RedirectToAction可以工作,但是当我尝试..../result?Type=我得到ArgumentNullException

Note: Adding None=0 in the Enum is not an option for me, I don not want none to show up in the dropdown list. 注意:在Enum中添加None=0对我来说不是一种选择,我不希望任何人都不会出现在下拉列表中。

How can I check for null in the controller? 如何在控制器中检查null? Is there a best practice in this regard? 在这方面是否有最佳实践?

Explicitly check whether the value is null before using it in IsDefined() . IsDefined()使用该值之前,先明确检查该值是否为null

public 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();
}

A shorter version is to use the null-coalesce operator to use 0 instead of null in the call to IsDefined() : 较短的版本是使用null-coalesce运算符在对IsDefined()的调用中使用0而不是null

public ActionResult Index(MyModel model)
{
    if(!Enum.IsDefined(typeof(MyEnum), model.EnumType ?? 0))
    {
        return RedirectToAction("Index", "Home");
    }           
    return View();
}

First, based on your model the Type property is required. 首先,根据您的模型,需要Type属性。

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

Second, you need to check that the enum value is really defined on the EnumType declaration, then you don't need to call Enum.isDefined method in your action. 其次,您需要检查EnumType声明中是否确实定义了枚举值,然后无需在操作中调用Enum.isDefined方法。 Just decorate your Type property with data annotation attribute EnumDataType(typeof(EnumType)) which will do that job. 只需使用数据注释属性EnumDataType(typeof(EnumType))装饰您的Type属性, EnumDataType(typeof(EnumType))完成该工作。 So your model will look like this: 因此,您的模型将如下所示:

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

Finally, in your controller action just clean it so it look this: 最后,在控制器操作中对其进行清理,使其看起来像这样:

// 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM