控制器方法中重新确认修改后的视图模型? [英] Revalidating a modified ViewModel within a controller method?
问题描述
修改 - 我们使用MVC4开发preVIEW ....
我执行一个 FishingTrip
类编辑页面。 FishingTrip
包含简单的船员
对象(即FishingTripID,CrewID,CrewPosition)的一个子集。
我使用贾勒特迈耶的做法添加编辑从船员
集合中删除。
我用不显眼的验证指定船员
都是要求
。
我的问题:当我从列表逻辑上删除一个项目(按贾勒特的方法),我不希望这样的项目进行验证
我已成功调整在客户端的removeRow的方法来禁用不显眼验证为逻辑上删除的项目,以便在窗体将张贴尽管有被包含空白字段的项目。
在我的控制器方法 [HttpPost]编辑
, ModelState.IsValid
开始了假(如预期 - 因为包含空字段的逻辑删除的项目。的)所以我从我的ViewModel删除项目....但 ModelState.IsValid
还是假的。
总之,我(我想)要修改控制器方法中我的ViewModel,删除违规项目,然后调用某种重新确认,并有 ModelState.IsValid
显示为真实的。
任何想法?
一旦你已经删除了违规项目(S),清除ModelState中,再次验证,像这样:
ModelState.Clear();
TryValidateModel(船员); //假设传递被命名为船员的模式
的注意的:因为这种方法不会验证模型嵌套的对象(如@Merenzo提到的)要当心在使用时 TryValidateModel
方法<。 / p>
EDIT - We're using MVC4 Dev Preview....
I'm implementing an edit page for a FishingTrip
class. FishingTrip
contains a child collection of simple Crew
objects (i.e. FishingTripID, CrewID, CrewPosition).
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
.
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.
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.
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.
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.
Any ideas?
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"
Note: Be carefull when use TryValidateModel
method because this method does not validate nested object of model (As mentioned by @Merenzo).
这篇关于控制器方法中重新确认修改后的视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!