2016-11-01 34 views
2

我已經得到了我使用的填充一個下拉我的形式的一部分,看起來像這樣的枚舉屬性:檢查枚舉財產空

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=5RedirectToAction作品,但是當我嘗試..../result?Type=我得到ArgumentNullException

注意:在Enum中添加None=0對我來說不是一個選項,我不希望沒有任何東西出現在下拉列表中。

如何在控制器中檢查空值?在這方面是否有最佳做法?

+0

它應該是'HasValue'?由於'Type'是一個可以爲空的' – Prisoner

回答

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

是的,它爲我工作。謝謝。 – hello

3

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使用0代替null在調用IsDefined()

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