1

Let's say I got the following Entity Framework "Ruimte" model:

public class Ruimte
{
    #region Constructor

    public Ruimte()
    {
        Kenmerken = new List<Kenmerk>();
    }

    #endregion

    #region Properties

    [Key]
    public int Id
    {
        get;
        set;
    }

    [Required]
    public string Naam
    {
        get;
        set;
    }


    public List<Kenmerk> Kenmerken
    {
        get;
        set;
    }

    #endregion
}

And the "Kenmerk" model looks the following:

public class Kenmerk
{
    #region Properties

    [Key]
    public int Id { get; set; }

    public KenmerkOptie KenmerkOptie
    {
        get;
        set;
    }

    [Required]
    public int KenmerkOptieId
    {
        get;
        set;
    }

    [Required]
    public string Waarde
    {
        get;
        set;
    }

    [Required]
    public int RuimteId
    {
        get;
        set;
    }

    #endregion
}

And in my Ruimte/Create view there are 2 fields for adding a "Kenmerk". Now a "Kenmerk" can't go into the database without having a KenmerkOptieId or Waarde. So the view will reject the submit everytime I try to post the form because of the validation. Though I want a "Ruimte" to have or not to have a "Kenmerk".

So the solution I went for was having a "RuimteCreateViewModel" with the properties "Name" which was required and a list of the another copmlex class called "KenmerkCreateViewModel". Now in this last viewmodel the KenmerkOptieId and the Waarde are not required so I finally CAN submit the form.

Though I don't think this is the best solution of "skipping" the required field validators. So what is your "best practice" when the database validation is different from the view validation?

4

1 に答える 1

1

I think xVal - a validation framework for ASP.NET MVC, see http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/ is very useful for the entity framework model that you are trying to develop. Especially the use of enforcing server-side validation, it allows you to choose to validate simple property formatting rules during property setters. See http://blog.stevensanderson.com/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/ for an explanation.

于 2012-12-11T10:46:10.260 に答える