在MVC模式的验证条件 [英] Conditional validation on model in MVC

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

问题描述

我有一个观点和放大器;模型,我使用的编辑和记录插入页两者。其中的业务需求是某一个领域,需要在编辑而不是新的。原来在此之前特定的功能被添加到案卷,我有模型像这样:

I have a view & model that I use for both the edit and the insert page for a record. One of the business requirements is that a certain field is required on edit but not on new. Originally before this particular feature was added to the docket, i had the model like so:

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

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

I would like to either remove the required property if it is an insert form, or add it if an edit form. What is the better approach? All my other validation is done like above. Or can I alter the model state? Thoughts?

修改

是我应该澄清的是,他们仍然允许新的,只是没有需要插入的代价。

Something I should clarify is that they are still permitted to insert a cost on new, just not required.

推荐答案

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

If you're on MVC3/.NET4, you can use IValidatableObject which exists specifically for such purposes.

引用<一个href=\"http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-$p$pview-1.aspx\">ScottGu,

...的IValidatableObject界面可以进行模型级
  验证,并允许您提供验证错误信息
  具体到整个模型的状态......

...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.");
        }
    }
}

和然后在控制器,

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


另外,最干净的解决办法是使用视图模型 - UpdateViewModel 在需要的属性,而 CreateViewModel 它不是必需的。


Otherwise, the most clean solution would be to use view models - UpdateViewModel where the property is required, and CreateViewModel where it's not required.

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

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