2011-10-18 14 views
1

私はMVCアプリケーションを持っています。特定のポイントで、私は手動でModelStateにエラーを追加しました。MVC ModelError値を取得する方法

ModelState.AddModelError("duplicateInvoiceNumberOrganisation", "The combination of organisation and invoice number must be unique"); 

私が知りたいのは、コントローラから後でエラーの値を取得する方法です。

私はでModelStateValuesに取得することができます知っている:

controller.ModelState.Values 

、それが言うので、それはそこにある:

Count = 1 
    [0]: {System.Web.Mvc.ModelState} 

をしかし、どのように、私は実際にそれのうち"The combination of organisation and invoice number must be unique"を得るのですか?

答えて

2
string error = ModelState["duplicateInvoiceNumberOrganisation"] 
    .Errors[0] 
    .ErrorMessage; 

またはそれに関連するエラーを持つ最初にModelState項目の最初のエラーを取得する:

string error = ModelState 
    .Where(x => x.Value.Errors.Count > 0) 
    .First() 
    .Value 
    .Errors[0] 
    .ErrorMessage; 
+0

クール、あなたの助けに感謝します。 – AnonyMouse

関連する問題