Amir133
Amir133

Reputation: 2692

validate an non-Input model in MVC core

I have an action-method that have an object type Input like this:

public async Task<IActionResult> DoSomeThing([FromBody]object input, bool options)

{
    if (options == true)
    {
        var castedInput = (A) input;
        if (TryValidateModel(castedInput))
        {
            // do some thing
        }
        else
        {
            //return validation Errors;
            //forexample:return Error("Error1")
            //??!??!!??!?!?!?!??!
        }
    }
    else
    {
        var castedInput = (B)input;
        if (TryValidateModel(castedInput))
        {
            // do some thing
        }
        else
        {
            //return validation Errors;
            //forexample:return Error("You must fill this parameter")
            //??!??!!??!?!?!?!??!

        }
    }
}

In this method first I cast Input to my ViewModel then validate it. now I want to return my Validation Errors that I set on annotations of my model. How can I do this?

My Viewmodels:

public class A
{
    [Required(ErrorMessage = "Error1")]
    string Phone;
    .
    .
    .
}

public class B
{
    [Required(ErrorMessage = "You must fill this parameter")]
    string Name;
    .
    .
    .  
}

Upvotes: 2

Views: 395

Answers (2)

Yiyi You
Yiyi You

Reputation: 18139

Here is a demo worked:

Action:

public JsonResult DoSomeThing([FromBody]object input,bool options)

        {
            var model = new Object();
            if (options)
            {
                model = JsonConvert.DeserializeObject<A>(input.ToString());
            }
            else {
                model = JsonConvert.DeserializeObject<B>(input.ToString());
            }
            string messages = "";
            if (!TryValidateModel(model))
            {
                messages = string.Join("; ", ModelState.Values
                                 .SelectMany(x => x.Errors)
                                 .Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
            }
            return Json(messages);
        }

Models:

public class A
    {
        [Required(ErrorMessage = "Error1")]
        public string Phone { get; set; }
    }

    public class B
    {
        [Required(ErrorMessage = "You must fill this parameter")]
        public string Name { get; set; }
     
    }

Result: enter image description here

Upvotes: 2

Sh.Imran
Sh.Imran

Reputation: 1033

Validation errors of DataAnnotation can be returned with ModelState object.

  • A generic function can be used and call it in every Action
protected string ValidateModel1()
{
    string messages = "";
    if (!ModelState.IsValid)
    {
        messages = string.Join("; ", ModelState.Values
                         .SelectMany(x => x.Errors)
                         .Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToSubString()));
    }
    return messages;
}
  • Use this method in controller as:
string modelState = ValidateModel();

2nd Way

Create an Action Filter and use it in Action Attribute or in Controller level:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            string messages = string.Join("; ", actionContext.ModelState.Values
                                                .SelectMany(x => x.Errors)
                                                .Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToSubString()));

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, messages);
        }
    }
}

Upvotes: 0

Related Questions