Reputation: 16851
I have created a webAPI and the datamodel
looks as follows:
{
"name" : "",
"age" : ""
}
Since this is a 3rd party API that I created, there'll be many other developers who'll be trying to access it. One of the common mistake they make is that they at times forget some of the fields in the datamodel
. For example, they may forget to enter a value for age
at all.
So they'll only send name
and not age
as shown below.
{
"name" : ""
}
How can I do a validation check from my controller to see if the developer has forgot to enter the attribute age
in the JSON ?
I tried checking for null, but it didn't work.
public async Task<IActionResult> SaveStudent([FromBody] Student stu)
{
if(stu.age == null) { DISPLAY ERROR } // This doesn't work
...
}
Upvotes: 1
Views: 67
Reputation: 32079
Your model class should be as follows:
public class Student
{
[Required]
public string Name {get; set;}
[Required]
public int Age {get; set;}
}
Then in the controller:
public class StudentController : Controller
{
public async Task<IActionResult> SaveStudent([FromBody] Student student)
{
if (ModelState.IsValid)
{
_dbContext.Students.Add(student);
await _dbContext.SaveChangesAsync();
return Json(true)
}
return Json(false);
}
}
Now you can show your custom error or success message on the client side based on SaveStudent()
method returned output.
Upvotes: 1
Reputation: 4354
You are looking for model validation Something like this;
public async Task<IActionResult> SaveStudent([FromBody] Student stu)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
...
}
Upvotes: 2
Reputation: 1307
As with most microsoft web frameworks, you can use DataAnnotatons , checking the MSDN website, you can find an example of how to use DataAnnotations with Json Post, using the attributes you can specify Range, Required, etc for the incoming model,
Upvotes: 3