Click here to Skip to main content
15,885,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
0
I have a method that accepts an Id parameter. I get the record from Database using that parameter and I have made some changes to the record.

Now, I want to validate those changes using "TryValidateModel" or "ValidateModel" and I want to get the list of errors if there is any to send them through API and not sending them to view.

I have been searching for a way to do that and most of the articles that I found are talking about getting them through "ModelState.Where". However, the record is not coming from a view.

Here is the method:

What I have tried:

public async Task<ActionResult> Anyname(int id)
        {
            // Get record
            var app = await db.Appointments.FindAsync(id);
            // Do some changes
            app.patFname = null;
            //..
            //..
            // check if model is valid
            bool isValid = TryValidateModel(app);
            if (!isValid)
            {
                // I want to get the list of error and send them back 
            }
            else
            {
                return new HttpStatusCodeResult(200);
            }
        }
Posted
Updated 28-Mar-21 22:54pm
v2

have a look to the sources:
GitHub MVC Controller

after calling TryValidationModel - you can get the errors via ModelState.
have a look to function below.

am sure you can modify that code for you specific needs.

protected internal bool TryValidateModel(object model, string prefix)
{
    if (model == null)
    {
        throw new ArgumentNullException("model");
    }

    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());

    foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, ControllerContext).Validate(null))
    {
        ModelState.AddModelError(DefaultModelBinder.CreateSubPropertyName(prefix, validationResult.MemberName), validationResult.Message);
    }

    return ModelState.IsValid;
}
 
Share this answer
 
Seems straight forward with passing the model instance to the TryValidateModel.
Just pass the instance of your model to check, something like below:
C#
UserInfo info = new UserInfo();
info.FirstName = "value from DB";
info.LastName = "known value";
info.BirthDate = DateTime.Parse("user provided value");

if(TryValidateModel(info))
{
       //Valid
       
}
else
{
       //InValid
}

Refer: Validate Model Programmatically in ASP.NET MVC | BinaryIntellect Knowledge Base[^]
 
Share this answer
 
Comments
Member 12701700 22-Jul-20 7:43am    
Naah, I was trying to grab the list of errors.
I know that TryValidateModel will check if it's valid or not,
I just want to get the error list if not valid.
I hope that makes it clear.
Thanks antway
Sandeep Mewara 22-Jul-20 8:19am    
You ned to use: ValidateSummary for it. Examples on web. see: https://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary
Member 12701700 22-Jul-20 9:32am    
No man, I am trying to get the list of errors in the controller not in the view,
I want to send them through API.
Got me :) thanks in advance
var errors = ModelState.Select(x => x.Value.Errors)
                           .Where(y=>y.Count>0)
                           .ToList();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900