我正在阅读NerDinner免费教程 http://nerddinnerbook.s3.amazonaws.com/Intro.htm
我到了第5步的某个地方,它说要使代码更清晰,我们可以创建一个扩展方法。我查看完成的代码,并使用扩展方法:
catch
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(new DinnerFormViewModel(dinner));
}
然后将此作为扩展方法的定义。
namespace NerdDinner.Helpers {
public static class ModelStateHelpers {
public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors) {
foreach (RuleViolation issue in errors) {
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
}
}
我尝试按照教程所说的内容结合代码包含的内容,但收到预期的错误,即没有AddModelErrors
方法只接受1个参数。
我显然在这里缺少一些非常重要的东西。它是什么?
答案 0 :(得分:11)
您需要包含助手参考;
using NerdDinner.Helpers;
和
using NerdDinner.Models;
然后检查有效并添加错误;
if (!dinner.IsValid)
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(dinner);
}
你必须为你的晚餐准备一个部分课程;
public partial class Dinner
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty( SomeField ))
yield return new RuleViolation("Field value text is required", "SomeField");
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
不要忘记RuleViolation
类;
public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation(string errorMessage)
{
ErrorMessage = errorMessage;
}
public RuleViolation(string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
答案 1 :(得分:3)
如果您收到与此海报相同的错误消息:
“'System.Web.Mvc.ModelStateDictionary'不包含'AddModelErrors'的定义,并且没有扩展方法'AddModelErrors'接受类型为'System.Web.Mvc.ModelStateDictionary'的第一个参数'(你是吗?)缺少using指令或程序集引用?)“
您可能遇到此问题: