在控制器方法中重新验证修改后的 ViewModel? [英] Revalidating a modified ViewModel within a controller method?

查看:29
本文介绍了在控制器方法中重新验证修改后的 ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑 - 我们正在使用 MVC4 Dev Preview....

EDIT - We're using MVC4 Dev Preview....

我正在为 FishingTrip 类实现一个编辑页面.FishingTrip 包含简单的 Crew 对象(即 FishingTripID、CrewID、CrewPosition)的子集合.

I'm implementing an edit page for a FishingTrip class. FishingTrip contains a child collection of simple Crew objects (i.e. FishingTripID, CrewID, CrewPosition).

我正在使用 Jarrett Meyer 的方法Crew 集合中添加、编辑和删除.我正在使用不显眼的验证来指定 Crew 的属性都是 Required.

I'm using Jarrett Meyer's approach to add, edit and delete from the Crew collection. I'm using unobtrusive validation to specify that the properties of Crew are all Required.

我的问题:当我从列表中逻辑删除一个项目时(按照 Jarrett 的方法),我不希望该项目得到验证.

My problem: when I logically-delete an item from the list (as per Jarrett's method), I don't want that item to be validated.

我已经成功地调整了客户端的removeRow"方法,以禁用对逻辑删除项目的不显眼的验证,这样尽管有一个包含空白字段的项目,表单也会发布.

I have successfully tweaked the "removeRow" method on the client-side to disable unobtrusive validation for the logically-deleted item, so that the form will post despite there being an item that contains blank fields.

在我的控制器方法 [HttpPost] Edit 中,ModelState.IsValid 以 false 开始(正如预期的那样 - 因为逻辑上删除的项目包含空白字段.)所以我从我的 ViewModel 中删除了那个项目......但 ModelState.IsValid 仍然是错误的.

In my controller method [HttpPost] Edit, ModelState.IsValid starts off as false (as expected - because of the logically-deleted item that contains blank fields.) So I remove that item from my ViewModel.... but ModelState.IsValid is still false.

总而言之,我(认为我)想在控制器方法中修改我的 ViewModel 以删除有问题的项目,然后调用某种重新验证",并让 ModelState.IsValid 显示为是真的.

In summary, I (think I) want to modify my ViewModel within the controller method to remove the offending item, then call some kind of "revalidate", and have ModelState.IsValid show up as true.

有什么想法吗?

推荐答案

删除违规项后,清除 ModelState 并再次验证,如下所示:

Once you have removed the offending item(s), clear the ModelState and validate again, like so:

ModelState.Clear();
TryValidateModel(crew);  // assumes the model being passed is named "crew"

注意:使用 TryValidateModel 方法时要小心,因为此方法不会验证模型的嵌套对象(如@Merenzo 所述).

Note: Be carefull when use TryValidateModel method because this method does not validate nested object of model (As mentioned by @Merenzo).

这篇关于在控制器方法中重新验证修改后的 ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆