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

时间:2015-05-19 09:02:30

标签: c# entity-framework validation asp.net-mvc-4

是否可以在ViewModel上放置条件,其中数据等于实体框架中一个字段中的特定值,在ViewModel上使用TryValidateModel之前,从ViewModel中删除了所需元素或整个对象?

我想从模型验证中删除HomeValue和PurchasePrice,其中OwnOrRent(model.OwnOrRent)不等于1或9。

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

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

正如您所看到的,我尝试使用ModelState.Remove,但这没有效果。

对此有何帮助将不胜感激?

2 个答案:

答案 0 :(得分:4)

根据您的评论,您希望从数据库填充模型,然后验证它(因为它的旧数据可能无效),但不会显示基于HomeValuePurchasePrice的错误OwnOrRent的值,在这种情况下,您需要先调用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();
    }
  }
}

您现在可以使用if (ModelState.IsValid)检查是否存在任何其他验证错误并返回相应的视图

附注:我刚刚使用了与if值相关的OwnOrRent条件,但我怀疑你真正想要的是

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

答案 1 :(得分:1)

有一个关于进行条件验证的不同选项的主题: ASP.NET MVC Conditional validation