禁止在某些情况下需要的验证属性 [英] Disable Required validation attribute under certain circumstances
问题描述
我想知道是否可以禁用某些控制器操作必需的验证属性。我想知道这一点,因为在我的编辑形式之一,我不要求用户对他们已经指定previously字段中输入值。不过,我再实现逻辑,当他们输入一个值,它使用了一些特殊的逻辑更新模型,如散列值等。
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屋!