4

我在操作结果中添加了一个键值对,如下所示:

[HttpPost,授权]
        公共 ActionResult ListFacilities(int countryid)
{
...
        ModelState.AddModelError("Error","该国家无设施报告!");
...
}

我在单元测试中有一些像这样的繁琐代码:

公共无效 ShowFailforFacilities()
 {
    //虚假数据
    var facility = controller.ListFacilities(1) as PartialViewResult;


    Assert.AreSame("在这个国家没有报告设施!",
        facility.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage);

 }

当然,只要我只有一个错误,它就可以工作。
我不喜欢facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage

有没有更简单的方法可以从该字典中获取值?

4

2 回答 2

13

不需要您的 FirstOrDefault,因为您在访问 ErrorMessage 时会收到 NullReferenceException。您可以只使用 First()。

无论哪种方式,我都找不到任何内置解决方案。我所做的是创建一个扩展方法:

public static class ExtMethod
    {
        public static string GetErrorMessageForKey(this ModelStateDictionary dictionary, string key)
        {
            return dictionary[key].Errors.First().ErrorMessage;
        }
    }

像这样工作:

ModelState.GetErrorMessageForKey("error");

如果您需要更好的异常处理,或支持多个错误,它很容易扩展......

如果您希望它更短,您可以为 ViewData 创建一个扩展方法...

public static class ExtMethod
    {
        public static string GetModelStateError(this ViewDataDictionary viewData, string key)
        {
            return viewData.ModelState[key].Errors.First().ErrorMessage;
        }
    }

和用法:

ViewData.GetModelStateError("error");
于 2011-04-11T07:26:46.040 回答
0

你试过这个吗?

// Note: In this example, "Error" is the name of your model property.
facilities.ViewData.ModelState["Error"].Value
facilities.ViewData.ModelState["Error"].Error
于 2011-04-11T06:59:51.700 回答