MVC 3剃刀部分验证模型 [英] MVC 3 Razor-Partial Validation of Model

查看:149
本文介绍了MVC 3剃刀部分验证模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MVC 3中开发一个项目,在这里我利用Entity Framework在两个视图中持有一个数据模型,每个视图包含一个HTML表单(类似于基于向导的设计)。



然而,在用户填写第一个View上的相应字段并提交表单后,将触发整个模型的客户端验证,并显示验证错误,这些字段甚至不可用于输入直到第二个视图实例化。



我目前已经实施了一个解决方法,我完全关闭第一个View的客户端验证,但我肯定不热衷于使用尚未被验证的数据填充我的模型的想法。这不好。 M'kay。



有没有办法部分验证第一个视图中的字段,而不是触发整个数据模型的valdiation?

解决方案

感谢您的输入。但是,我能够以非常简单的方式获得解决方案。通过将以下代码放入第一个View的HttpPost元素...



if(ModelState.IsValidField(FirstField)& amp ; ModelState.IsValidField(SecondField))
返回RedirectToAction(NameOfAction,model);
else
return View();



...我能够实现部分字段验证。但是,仅当第一个View具有取消类别的提交按钮,并且生成的附加验证错误(对于第一个视图中不存在的字段)在上述之前手动清除if语句。为此,请使用:

  ModelState [FieldName]。Errors.Clear(); 

建筑物没有重大变化。没有部分视图。没有递交未验证的数据。



工作得很好...



注意:如果第二个视图加载验证错误,使用:



ModelState.Clear();


$ b $最初调用第二个视图的Action中的b

。这将使第二个View加载清除和无错误,同时仍然在最终表单提交后仍显示验证错误。


I am currently working on a project in MVC 3 where I am leveraging Entity Framework to persist one data model over two Views which each contain one HTML Form (similar to wizard-based design).

Yet after the user fills out the appropriate fields on the first View and submits the form, client-side validation for the entire model is triggered, and validation errors are shown for fields that will not even be available for input until the second View instantiates.

I have currently implemented a workaround where I simply turn off client-side validation for the first View entirely, but I am certainly not keen on the idea of populating my model with data that has not been validated at all. This is bad. M'kay.

Is there any way to partially validate the fields on the first View and not trigger valdiation for the whole data model?

解决方案

Thanks for the input all. However, I was able to obtain a solution in a very simple way. By placing the following code in the HttpPost element of the first View...

if (ModelState.IsValidField("FirstField") && ModelState.IsValidField("SecondField")) return RedirectToAction ("NameOfAction", model); else return View();

...I was able to achieve partial field validation. However, this field-specific approach will ONLY work provided the Submit button on the first View has class "cancel" and the additional validation errors that are generated (for the fields that are NOT present on the first View) are manually cleared before the above if statement. To do this, use:

ModelState["FieldName"].Errors.Clear();

No major change in architecure. No partial Views. No handing off unvalidated Data.

Works very well...

NOTE: If the second View loads with validation errors, use:

ModelState.Clear();

in the Action where the second View is initially called. This will make the second View load clean and error free, while still showing the validation errors later upon final form submission.

这篇关于MVC 3剃刀部分验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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