2011-05-19 46 views
2

我正在使用第三方组件来调用传递模型对象的方法,如果发现任何错误,它将调用传递一个ValidationResult数组的回调方法。我想要做的是设置这些错误,以便Html.TextBoxFor将呈现属性class =“input-validation-error”。现在,我用我需要的验证属性来装饰我的模型类,如果名称为空,它将按预期工作,并使名称输入为红色,但如果组件表示它由于任何原因而无效,我有一个新的foreach循环,将打印错误消息...以编程方式为MVC创建自定义错误

我想在这个回调方法中做一些事情,这将使我的视图工作,就像我用验证属性装饰我的模型类一样。 ..

这可能吗?

谢谢!

回答

1

您可以在控制器内使用ModelState.AddModelError(string,string)。

// .. the model 
public class MyModel { public string Property { get; set; } } 

// .. in the controller 
public ActionResult DoSomething(MyModel x) 
{ 
    if(x.Property == "2") 
    { 
     ModelState.AddModelError("Property", "2 is not allowed"); 
     return View("EditorView", x); 
    } 
    // else.... 
} 
+0

正是我所需要的!谢谢! – Bruno 2011-05-19 22:36:44

相关问题