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

编程入门 行业动态 更新时间:2024-10-27 11:23:18
在某些情况下禁用必需的验证属性(Disable Required validation attribute under certain circumstances)

我想知道是否可以在某些控制器操作中禁用Required validation属性。 我想知道这一点,因为在我的一个编辑表单中,我不需要用户输入他们以前指定的字段的值。 然而,我然后实现逻辑,当他们输入一个值时,它使用一些特殊的逻辑来更新模型,例如哈希值等。

任何关于如何解决这个问题的意见?

编辑: 是的,客户端验证是一个问题,因为它不允许他们提交表单而不输入值。

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?

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

最满意答案

使用视图模型可以很容易地解决这个问题。 视图模型是专门针对给定视图的需求量身定制的课程。 所以例如在你的情况下,你可以有以下视图模型:

public UpdateViewView { [Required] public string Id { get; set; } ... some other properties } public class InsertViewModel { public string Id { get; set; } ... some other properties }

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

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

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) { ... }

更多推荐

validation,输入,电脑培训,计算机培训,IT培训"/> <meta name="description&quo

本文发布于:2023-07-14 23:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1108375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   情况下   在某些   Disable   circumstances

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!