MVC 模型验证
我有一个视图绑定到带有 DataAnnotations 的 ViewModel 进行验证,并且我有一个带有模型输入参数的操作(用于 ModelBinding)。我的代码看起来像......
public ActionResult MyMethod (MyModelDefinition model, string ddlValue){
if (ModelState.IsValid) { return RedirectToAction ("...");}
// If my model is not valid i want to change it and return the View Again...
model.field1 = "xpto";
return View(model);
}
当我这样做时,我遇到了验证错误(即使在我的 field1 中女巫是必需的,我在渲染视图之前填充它)。
我缺少什么?
谢谢大家..
I have a View binded to a ViewModel with DataAnnotations for validation and i have an Action with Model input parameter (for ModelBinding). My code looks like...
public ActionResult MyMethod (MyModelDefinition model, string ddlValue){
if (ModelState.IsValid) { return RedirectToAction ("...");}
// If my model is not valid i want to change it and return the View Again...
model.field1 = "xpto";
return View(model);
}
When i do this i have validation errors (even in my field1 witch is a required one and i fill it before my View was rendered).
What i'm missing?
Thank U All..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您打算在控制器中修改该值,或者在渲染视图时,用于渲染该值的 HTML 帮助程序将首先在 POSTed 值中查找,然后在模型中查找,则需要从模型状态中删除该值。这是预期的行为。
You need to remove the value from the model state if you intend to modify it in the controller or when you render the view the HTML helper that you have used to render this value will first look in the POSTed values and after that in the model. That's the expected behavior.