简体   繁体   English

使用实体框架的MVC 4条件模型验证

[英]MVC 4 Conditional Model Validation with Entity Framework

Is it possible to place conditions on a ViewModel where data equals a specific value in one field within the entity framework, the required element or entire object is removed from the ViewModel before using TryValidateModel on the ViewModel? 是否可以在ViewModel上放置条件,其中数据等于实体框架内一个字段中的特定值,在ViewModel上使用TryValidateModel之前,从ViewModel中删除了所需元素或整个对象?

I would like to remove HomeValue and PurchasePrice from the Model validation where OwnOrRent (model.OwnOrRent) is not equal to 1 or 9. 我想从模型验证中删除HomeValue和PurchasePrice,其中OwnOrRent(model.OwnOrRent)不等于1或9。

Model.cs Model.cs

public class Address
{
    public int Id { get; set; }

    [DisplayName("House Name or Number")]
    [StringLength(50)]
    public string HouseNameOrNumber { get; set; }

    [DisplayName("Post Town")]
    [StringLength(50)]
    public string PostTown { get; set; }

    [Required(ErrorMessage = "Own or Rent is Required")]
    [DisplayName("Own or Rent")]
    [StringLength(50)]
    public string OwnOrRent { get; set; }

    [Required(ErrorMessage = "Mortgage/Rent Amount is Required")]
    [DisplayName("Mortgage/Rent Amount")]
    [StringLength(50)]
    public string MortgageRent { get; set; }

    [Required(ErrorMessage = "Home Value is Required")]
    [DisplayName("Home Value")]
    [StringLength(50)]
    public string HomeValue { get; set; }

    [Required(ErrorMessage = "Purchase Price is Required")]
    [DisplayName("Purchase Price")]
    [StringLength(50)]
    public string PurchasePrice { get; set; }
}

HomeController.cs HomeController.cs

public ActionResult Application(int id)
{
    var viewAddressModel = new Address();

    using (
        var dbEntities = new DbEntities(new EntityConnection(_df.DbEntities)))
    {
        var model = dbEntities.Applications.Single(e => e.Id == id);

        viewAddressModel.Id = Id;
        viewAddressModel.HouseNameOrNumber = model.HouseNameOrNumber;
        viewAddressModel.PostTown = model.PostTown;
        viewAddressModel.OwnOrRent = GetStatus(model.OwnOrRent);
        viewAddressModel.MortgageRent = model.MortgageRent.ToString();
        viewAddressModel.HomeValue = model.HomeValue;
        viewAddressModel.PurchasePrice = model.PurchasePrice;

        if (model.OwnOrRent != "1" || model.OwnOrRent != "9")
        {
            ModelState.Remove("HomeValue");
            ModelState.Remove("PurchasePrice");
        }

        if (!TryValidateModel(viewAddressModel))
        {
            return PartialView("Address", viewAddressModel);
        }
    }

    var vm = new ApplicationViewModel { Item = CreateApp(id) };

    return PartialView("Application", vm);
}

As you can see I have tried to use ModelState.Remove but this has no effect. 正如您所看到的,我尝试使用ModelState.Remove,但这没有任何效果。

Any assistance with this would be much appreciated? 对此有何帮助将不胜感激?

Based on your comments you want to populate a model from the database, then validate it (because its old data which may not be valid), but not display errors for HomeValue or PurchasePrice based on the value of OwnOrRent, in which case you need to call TryValidateModel first, then remove ModelState errors 根据您的注释,您希望从数据库填充模型,然后验证它(因为它的旧数据可能无效),但不会根据OwnOrRent的值显示HomeValuePurchasePrice的错误,在这种情况下您需要首先调用TryValidateModel ,然后删除ModelState错误

var viewAddressModel = new Address();
.... // set values
if (!TryValidateModel(viewAddressModel))
{
  if (model.OwnOrRent != "1" || model.OwnOrRent != "9")
  {
    if (ModelState.ContainsKey("HomeValue"))
    {
      ModelState["HomeValue"].Errors.Clear();
    }
    if (ModelState.ContainsKey("PurchasePrice"))
    {
      ModelState["PurchasePrice"].Errors.Clear();
    }
  }
}

You can now use if (ModelState.IsValid) to check if there are any other validation errors and return the appropriate view 您现在可以使用if (ModelState.IsValid)来检查是否存在任何其他验证错误并返回相应的视图

Side note: I just used your if condition relating to the OwnOrRent value, but I suspect what you really want is 旁注:我刚刚使用了与OwnOrRent值相关的if条件,但我怀疑你真正想要的是什么

if (!(model.OwnOrRent == "1" || model.OwnOrRent == "9"))

有一个关于进行条件验证的不同选项的线程: ASP.NET MVC条件验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM