Validating MVC 4 Conditional Model with Entity Framework

Is it possible to place conditions on the ViewModel where the data is equal to a specific value in one field within the entity, the desired element, or the entire object is removed from the ViewModel before using TryValidateModel in the ViewModel?

I would like to remove HomeValue and PurchasePrice from model validation where OwnOrRent (model.OwnOrRent) is not 1 or 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);
}

      

As you can see, I tried using ModelState.Remove, but that has no effect.

Any help with this would be much appreciated?

+3


source to share


2 answers


Based on your comments, you want to populate the model from the database, then validate it (as its old data may not be valid), but do not display errors for HomeValue

or PurchasePrice

based on the OwnOrRent value, in which case you need to call TryValidateModel

and then remove ModelState

errors

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

      

Now you can use if (ModelState.IsValid)

to check for other validation errors and return the appropriate view



Side note: I just used your condition if

referring to the value OwnOrRent

, but I suspect you really want

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

      

+3


source


There are a stream of different options for doing conditional validation: ASP.NET MVC Conditional Validation



+1


source







All Articles