我已經得到了我使用的填充一個下拉我的形式的一部分,看起來像這樣的枚舉屬性:檢查枚舉財產空
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
對我來說不是一個選項,我不希望沒有任何東西出現在下拉列表中。
如何在控制器中檢查空值?在這方面是否有最佳做法?
它應該是'HasValue'?由於'Type'是一個可以爲空的' – Prisoner