有条件的验证对ASP MVC视图模型场 [英] Conditional Validation for ViewModel Fields on ASP MVC

查看:92
本文介绍了有条件的验证对ASP MVC视图模型场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题:关于ASP MVC视图模型场条件验证

Title: Conditional Validation for ViewModel Fields on ASP MVC

我有一个关于ASP MVC validtion问题。比方说,我有follwing视图模型

I have a question about ASP MVC validtion. Let's say that I have the follwing View Model

public class PersonViewModel
{
    [Required]
    public string Name {get; set; }

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

根据这个,当我提交表单MVC将验证这两个领域都值。然而,在我的网站我有那里的电子邮件可以在全球站点设置被关闭,因此该模型将只会使名称的文本框表单上的情况。现在,当我提交表单它仍然要求我的电子邮件字段,因为它表示为必需,尽管是没有办法的用户现在可以填补这一领域。

According to this when I submit the form MVC will validate that both fields have values. However, in my website I have the situation where the Email can be turned off in a global site setting, so the model will only render the Name Textbox on the form. Now when I submit the form it still asks me for the Email field since it is indicated as "Required", despite there is no way the user can fill that field now.

有没有使用ASP MVC验证时,这种类型的场景的解决方案?

Is there a solution for this type of scenario when using ASP MVC validations?

推荐答案

我似乎已经找到了解决办法:

I seem to have found the solution:

if(EmailTurnedOff)
{
    this.ViewData.ModelState.Remove("Email");
}

然后当我打电话ModelState.IsValid它会给我正确的答案

Then when I call ModelState.IsValid it will give me the correct answer

这篇关于有条件的验证对ASP MVC视图模型场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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