dtc*_*dtc 4 asp.net-mvc extension-methods nerddinner
我正在阅读NerDinner免费教程 http://nerddinnerbook.s3.amazonaws.com/Intro.htm
我到了第5步的某个地方,它说要使代码更清晰,我们可以创建一个扩展方法.我查看完成的代码,并使用扩展方法:
catch
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(new DinnerFormViewModel(dinner));
}
Run Code Online (Sandbox Code Playgroud)
然后这作为扩展方法的定义.
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试按照教程所说的结合代码包含的内容,但收到预期的错误,即没有AddModelErrors方法只接受1个参数.
我显然在这里缺少一些非常重要的东西.它是什么?
gri*_*egs 11
你需要包括助手参考;
using NerdDinner.Helpers;
Run Code Online (Sandbox Code Playgroud)
和
using NerdDinner.Models;
Run Code Online (Sandbox Code Playgroud)
然后检查有效并添加错误;
if (!dinner.IsValid)
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(dinner);
}
Run Code Online (Sandbox Code Playgroud)
您还必须为您的晚餐准备一个部分课程;
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");
}
}
Run Code Online (Sandbox Code Playgroud)
别忘了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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3052 次 |
| 最近记录: |