【发布时间】:2010-01-21 00:18:18
【问题描述】:
谁能告诉我为什么这个 try catch 不能捕捉到名词模型中的问题?
我现在已经在两种不同的控制器方法上尝试过这个,而且两次,即使 linq2sql 不允许保存数据,代码也永远不会跳转到 catch 块中。
我看过trace中间的名词对象,isvalid属性为假,而modelstate isvalid为真。无论哪种方式,代码都不会跳转到 catch 块中。
我对此感到很恼火。我觉得这将是一件非常愚蠢的事情。
代码的工作方式都类似于书呆子晚餐。
NounRepository nounRepository = new NounRepository();
Noun noun = new Noun();
try
{
UpdateModel(noun);
nounRepository.Add(noun);
nounRepository.save();
}
catch (Exception ex)
{
ModelState.AddRuleViolations(noun.GetRuleViolations());
return View(noun);
}
return View(noun);
更新
我刚刚添加了这段代码,现在规则回到前端很好,所以看起来try catch没有捕捉到!
UpdateModel(noun);
if (!noun.IsValid)
{
var errors = noun.GetRuleViolations();
ModelState.AddRuleViolations(noun.GetRuleViolations());
return View(noun);
}
nounRepository.Add(noun);
nounRepository.save();
我宁愿不必以这种方式添加代码,因为这似乎是不必要的重复。
【问题讨论】:
标签: asp.net asp.net-mvc validation model