作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个枚举属性,用于填充下拉列表作为表单的一部分,如下所示:
public class MyModel
{
[Required]
[DisplayName("Type of Enum")]
public EnumType? Type { get; set; }
}
public enum EnumType
{
option1 = 1,
option2 = 2,
option3 = 3,
option4 = 4
}
表单提交到另一个 Controller ,我在其中尝试检查枚举类型中的 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
对我来说不是一个选项,我不希望下拉列表中没有显示任何内容。
如何检查 Controller 中的空值?这方面有最佳实践吗?
最佳答案
在 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 operator在调用 IsDefined()
时使用 0
而不是 null
:
public ActionResult Index(MyModel model)
{
if(!Enum.IsDefined(typeof(MyEnum), model.EnumType ?? 0))
{
return RedirectToAction("Index", "Home");
}
return View();
}
关于c# - 检查枚举属性中是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40354003/
我是一名优秀的程序员,十分优秀!