繁体   English   中英

检查枚举属性是否为空

[英]Check for null in enum property

我有一个枚举属性,用于在我的表单中填充一个下拉列表,如下所示:

 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

注意:在Enum中添加None=0对我来说不是一种选择,我不希望任何人都不会出现在下拉列表中。

如何在控制器中检查null? 在这方面是否有最佳实践?

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

较短的版本是使用null-coalesce运算符在对IsDefined()的调用中使用0而不是null

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

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

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

其次,您需要检查EnumType声明中是否确实定义了枚举值,然后无需在操作中调用Enum.isDefined方法。 只需使用数据注释属性EnumDataType(typeof(EnumType))装饰您的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();
}

暂无
暂无

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

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