Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8712211
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T05:03:51+00:00 2026-06-13T05:03:51+00:00

Problem I know there is a lot of ways of doing Model validation within

  • 0

Problem

I know there is a lot of ways of doing Model validation within MVC, and there is quite a lot of documentation regarding this topic. However, I’m not quite sure what’s the best approach for validating properties of the Model which are “Sub Model” of same type.

Keep in mind the following

  • I still want to to take profit of the TryUpdateModel/TryValidateModel methods
  • Each of these “sub models” have strongly typed views
  • There is one strongly typed view for the MainModel class that renders the overall display view

It might sound a little confusing but i’ll throw in some code to clarify. Take as example the following classes:

MainModel:

class MainModel{
    public SomeSubModel Prop1 { get; set; }
    public SomeSubModel Prop2 { get; set; }
}

SomeSubModel:

class SomeSubModel{
      public string Name { get; set; }
      public string Foo { get; set; }
      public int Number { get; set; }
}

MainModelController:

class MainModelController{

    public ActionResult MainDisplay(){
         var main = db.retrieveMainModel();
         return View(main); 
    }

    [HttpGet]
    public ActionResult EditProp1(){
         //hypothetical retrieve method to get MainModel from somewhere
         var main = db.retrieveMainModel();

         //return "submodel" to the strictly typed edit view for Prop1
         return View(main.Prop1);
    }

    [HttpPost]
    public ActionResult EditProp1(SomeSubModel model){

         if(TryValidateModel(model)){
              //hypothetical retrieve method to get MainModel from somewhere
              var main = db.retrieveMainModel();
              main.Prop1 = model;
              db.Save();

              //when succesfully saved return to main display page 
              return RedirectToAction("MainDisplay");
         }
         return View(main.Prop1);
    }

    //[...] similar thing for Prop2 
    //Prop1 and Prop2 could perhaps share same view as its strongly 
    //typed to the same class
}

I believe this code all make sense until now (correct me if it’s not the case) because TryValidateModel() is validating against a model with no ValidationAttribute.

The problem lies here, where would be the best place, or what would be the best and most elegant way to have different validation constraints for Prop1 and Prop2 while still taking advantage of TryValidateModel() and not filling the Edit method with conditional statements and ModelState.AddModelError()

Usually you could have validation attributes in the SomeSubModel class, but it wouldn’t work in this case, because there is different constraints for each property.

Other option is that there could be Custom validation attribute in the MainModel class, but it also wouldn’t work in this case because the SomeSubModelobject is passed directly to the view and when validating has no reference to its MainModel object.

The only left option I can think about is a ValidationModel for each property, but I am not quite what would be the best approach for this.

Solution

Here’s solution I implemented, based of @MrMindor’s answer.

Base ValidationModel class:

public class ValidationModel<T> where T : new()
{
    protected ValidationModel() {
        this.Model = new T();
    }
    protected ValidationModel(T obj) { 
        this.Model = obj; 
    }

    public T Model { get; set; }
}

Validation Model for Prop1

public class Prop1ValidationModel:ValidationModel<SomeSubModel>
{
    [StringLength(15)]
    public string Name { get{ return base.Model.Name; } set { base.Model.Name = value; } }

    public Prop1ValidationModel(SomeSubModel ssm)
        : base(ssm) { }
}

Validation Model for Prop2

public class Prop2ValidationModel:ValidationModel<SomeSubModel>
{
    [StringLength(70)]
    public string Name { get{ return base.Model.Name; } set { base.Model.Name = value; } }

    public Prop2ValidationModel(SomeSubModel ssm)
        : base(ssm) { }
}

Action

[HttpPost]
public ActionResult EditProp1(SomeSubModel model){

     Prop1ValidationModel vModel = new Prop1ValidationModel(model);
     if(TryValidateModel(vModel)){

          //[...] persist data

          //when succesfully saved return to main display page 
          return RedirectToAction("MainDisplay");
     }
     return View(model);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T05:03:52+00:00Added an answer on June 13, 2026 at 5:03 am

    We have a similar situation in one of our applications where each SomeSubModel represents a parameter setting for a job. As each type of job has a different number and types of parameters, our job model has a collection of these parameters instead of just having set properties.

    We have a JobParameter that is subclassed into the different types available (StringParameter, BoolParameter, DoubleParameter, …). These subclasses have their own sets of validation attributes.
    A shared ‘JobParameterModel’ is used for passing the parameters to the view.
    For Validation the returned Model is converted to its specific JobParameter.
    ParameterTypes:

    public enum ParameterType
    {
        Empty = 0,
        Boolean = 1,
        Integer = 2,
        String = 3,
        DateTime = 4,
        ...
    }
    

    JobParameter:

    class JobParameter
    { 
      [AValidationAttributeForAllParamters] 
      public string Name { get; set; }  
      public virtual string Foo { get; set; }  
      public int Number { get; set; }
      public ParameterType Type {get;set;}
    
      private static readonly IDictionary<ParameterType, Func<object>> ParameterTypeDictionary =
      new Dictionary<ParameterType, Func<object>>{
                    {ParameterType.Empty, () => new EmptyParameter() },
                    {ParameterType.String, ()=>new StringParameter()},
                    {ParameterType.Password, ()=>new PasswordParameter()},
                    ...
                  };
        public static ScriptParameter Factory(ParameterType type)
        {
            return (ScriptParameter)ParameterTypeDictionary[type]();
        }
    }  
    

    BoolParameter:

    [ABoolClassLevelValidationAttribute]
    class BoolParameter:JobParameter
    {
        [AValidationAttribute]
        public override string Foo {get;set;}
    }
    
    ....
    

    In our validation framework (which I am told is modeled very closely to MS’s) the ViewModel is always converted back to its domain object for validation.
    ParameterModel:

    class ParameterModel: JobParameter
    {
        public JobParameter ToDomain()
        {
            var domainObject = JobParameter.Factory(Type);
            Mapper.Map(this, domainObject);
            return domainObject;
        }
        public bool Validate()
        {
            var dom = ToDomain();
            return TryValidate(dom);
        }
    
    }
    

    Controller:

    class Controller(){
    
        [HttpPost]                                
        public ActionResult SaveParameter(JobParameter model){                                
    
             if(TryValidateModel(model)){                                
    
                  //persist stuff to db.
    
              //when succesfully saved return to main display page                                 
                  return RedirectToAction("MainDisplay");                                
             }                                
             return View(main.Prop1);
        }                                
    }                                
    

    For the sake of your specific situation, you don’t need to get quite this complicated (Or trust that the specifics of our validation framework will work for you).
    Edit/Save Actions for each Prop:
    Create a validation model for each prop. Prop1ValidationModel, Prop2ValidationModel

    [HttpGet]
    public ActionResult EditProp1()
    {
        var main = db.retrieveMainModel();
        db.Prop1.SubmitUrl = Url.Action("SaveProp1","Controller");
        return View(main.Prop1);
    }
    [HttpPost]                                
    public ActionResult SaveProp1(SomeSubModel model){                                
         var validationModel = new Prop1ValidationModel{
         ///copy properties                                   
             };
         if(TryValidateModel(validationModel)){                                
    
              var main = db.retrieveMainModel();                                
              main.Prop1 = model;                                
              db.Save();                                
    
              //when succesfully saved return to main display page                                 
              return RedirectToAction("MainDisplay");                                
         }                                
         return View(main.Prop1);
    } 
    

    With this you can use the same strongly typed view for both Prop1 and Prop2.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know there is a lot of thread about this problem but I dont
I know there's a lot of questions about this topic but I have not
I know there's a lot of posts with the same that problem. I just
I know there are similar questions about this topic,but somehow I'm not able to
I know there are a lot of questions around this subject, but I cannot
I know there's a lot of other questions out there that deal with this
I know there are a LOT of this question on here. I took a
I know there are a lot of questions like this on the forums, but
I know there were earlier problems with this in < 4.7.4 Qt versions. has
I don't know where to look for about this problem ... I have three

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.