Partial validation of ASP.NET MVC 3 Models

I have a very large 60+ question form that the user can start to fill, save at any point and leave it in hold. The form can be reloaded from the database and completed any time and then close it.

I have the following model:

public class Questionnaire{

  [Required]
  public string Question1 { get; set; }

  [Required]
  [Range(1, 10)]
  public int Quesiton2 { get; set; }

  public string Question3 {get;set}
}

I need to partially validate my model when the user decides to save the form and perform a full validation including the validation of the required fileds when the user chose to close the form.

what is the best way to implement it ?


Its not totally clear from your question / example exactly what you need, but I have found generally that splitting up my View Models in MVC is the best way to approach this kind of thing.

ie split up your entity into parts, each of which can be validated on its own.

Then use partial views / custom editor templates to provide the UI components for each of these.

Then you can either combine these components in one form when needed, or provide separate forms on same page, multi page wizards, or single page progressive AJAX wizards, or whatever you want) as needed.

Keeps things DRY and simple.

Key is to not be afraid to add the extra layer of View Models when needed, to bring your data objects in line with the requirements of your UI .

Don't be constrained by your business objects / entities when you specifically need to be free of them - its easy enough to put the parts of a business object back together from constituent View Model pieces.


你为什么使用Question1 .. Questionn ..每个问题1个对象,如果你添加一个新的问题?...你应该有一个问题列表,然后根据你的业务规则保存之前手动验证。


你可以在Save()上有两个单独的动作Save()和Submit()并禁用验证(或者做最小限度的验证)。

链接地址: http://www.djcxy.com/p/5178.html

上一篇: Matcher在匹配后抛出IllegalStateException

下一篇: ASP.NET MVC 3模型的部分验证