在ASP MVC3中将[RequiredIf]与ViewModels一起使用 [英] Using [RequiredIf] in ASP MVC3 with ViewModels

查看:93
本文介绍了在ASP MVC3中将[RequiredIf]与ViewModels一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我有一个像这样传递给视图的视图模型:

I have a viewmodel which is passed to the view like this:

public class HistoryViewModel
{
    public Contact ContactModel { get; set; }
    public Account AccountModel { get; set; }
    public Person PersonModel { get; set; }
 }

我有一堆带有所有道具的模型(即contact.cs,account.cs,person.cs)

I have a bunch of models with all the props in them (i.e. contact.cs, account.cs, person.cs)

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsAdult { get; set; }        
    [RequiredIf("IsAdult", "Yes", Errormessage="Please leave a comment")]
    public string Comments { get; set; }
 }

通过视图模型传递时,RequiredIf验证似乎不起作用.如果我将属性直接从模型通过ViewModel移到ViewModel中,则效果很好.

The RequiredIf validation does not seem to be working when passed through the viewmodel. It works fine if I move the properties into the viewmodel directly. All other[Required]` attributes work from the model, through the viewmodel.

那么我是否需要将所有属性都移到viewModel中,这需要在它们上使用RequiredIf?还是有其他解决方法?

推荐答案

您是否尝试过 MVC FoolProof验证?它在客户端支持下支持RequiredIf(以及其他少数几个).有时可能会有些bug,但是最新版本还不错.

Have you tried MVC FoolProof validation? It has support for RequiredIf (and a fair few others) with Client Side support. It can sometimes be a bit buggy but latest version isn't to bad.

以与上述相同的方式工作(在切换到FoolProof之前,我曾尝试过这种方式)

Works in same way as the above (which I tried before I switched to FoolProof)

   public bool Married { get; set; }

    [RequiredIfTrue("Married")]
    public string MaidenName { get; set; }

这篇关于在ASP MVC3中将[RequiredIf]与ViewModels一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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