Reputation: 2692
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
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; }
}
Upvotes: 2
Reputation: 1033
Validation errors of DataAnnotation
can be returned with ModelState
object.
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;
}
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