gpt4 book ai didi

asp.net-mvc - MVC中模型的条件验证

转载 作者:行者123 更新时间:2023-12-03 14:33:09 25 4
gpt4 key购买 nike

我有一个 View 和模型,可用于记录的编辑和插入页面。业务需求之一是编辑需要某个字段,但新字段不需要。最初,在将此特定功能添加到摘要之前,我有这样的模型:

[Required(ErrorMessage = "*")]
[Range(0.0, (double)decimal.MaxValue)]
[DisplayName("Cost")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public decimal ProposedCost { get; set; }

如果是插入表单,我想删除所需的属性,或者如果是编辑表单,则添加它。什么是更好的方法?我所有的其他验证都像上面一样完成。或者我可以改变模型状态吗?想法?

编辑

我应该澄清的一点是,他们仍然可以在新的上插入成本,只是不需要。

最佳答案

如果你使用的是 MVC3/.NET4,你可以使用 IValidatableObject专门为此目的而存在。

报价ScottGu ,

...The IValidatableObject interface enables you to perform model-level validation, and enables you to provide validation error messages specific to the state of the overall model....



你的模型看起来像
public class MyViewModel : IValidatableObject
{
public long? Id { get; set; }
public decimal? ProposedCost { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Id != null && ProposedCost == 0) {
yield return new ValidationResult("ProposedCost must be provided.");
}
}
}

然后在 Controller 中,
[HttpPost]
public ActionResult Submit(MyViewModel model)
{
if (!ModelState.IsValid) {
//failed - report an error, redirect to action etc
}
//succeeded - save to database etc
}

否则,最干净的解决方案是使用 View 模型 - UpdateViewModel需要该属性的地方,以及 CreateViewModel不需要的地方。

关于asp.net-mvc - MVC中模型的条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17970584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com