在某些情况下禁用必需的验证属性 [英] Disable Required validation attribute under certain circumstances

查看:37
本文介绍了在某些情况下禁用必需的验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在某些控制器操作中禁用必需的验证属性.我想知道这一点,因为在我的其中一个编辑表单上,我不需要用户为他们之前已经指定的字段输入值.但是,我随后实现了这样的逻辑:当他们输入一个值时,它使用一些特殊的逻辑来更新模型,例如散列值等.

I was wondering if it is possible to disable the Required validation attribute in certain controller actions. I am wondering this because on one of my edit forms I do not require the user to enter values for fields that they have already specified previously. However I then implement logic that when they enter a value it uses some special logic to update the model, such as hashing a value etc.

有关如何解决此问题的任何建议?

Any sugestions on how to get around this problem?


是的,客户端验证在这里是一个问题,因为它不允许他们在不输入值的情况下提交表单.


And yes client validation is a problem here to, as it will not allow them to submit the form without entering a value.

推荐答案

这个问题可以通过使用视图模型轻松解决.视图模型是专门针对给定视图的需求量身定制的类.因此,例如在您的情况下,您可以拥有以下视图模型:

This problem can be easily solved by using view models. View models are classes that are specifically tailored to the needs of a given view. So for example in your case you could have the following view models:

public UpdateViewView
{
    [Required]
    public string Id { get; set; }

    ... some other properties
}

public class InsertViewModel
{
    public string Id { get; set; }

    ... some other properties
}

将在其相应的控制器操作中使用:

which will be used in their corresponding controller actions:

[HttpPost]
public ActionResult Update(UpdateViewView model)
{
    ...
}

[HttpPost]
public ActionResult Insert(InsertViewModel model)
{
    ...
}

这篇关于在某些情况下禁用必需的验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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