Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

{Required] Attribute is not working on Lists ASP.NET WebAPI

Here’s my model

 public class TaskForUpdateDTO
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Name { get; set; }
}

and my controller

    [HttpPut]
    public ActionResult<List<TaskDTO>> Put([FromBody] List<TaskForUpdateDTO> tasks )
    {
        List<TaskBO> tasksForUpdate = TaskForUpdateDTO.MapToBOList(tasks);
        tasksForUpdate = _serviceManager.TaskService.Update(tasksForUpdate);

        if (tasksForUpdate is null) return NotFound();

        return Ok(TaskDTO.MapToDTOList(tasksForUpdate));
    }

and body of my request

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    [{
    "Name":"Do Laundry",
    "UserId":1
     },
     {
    "Name":"Wash Dishes",
    "UserId":1
    }]

when sending a PUT request, I’m not getting a 400 error , which I should because I’m not sending the Id of the item.

how can I fix this?

>Solution :

The Required Attribute only check for null.
The Default value of an int is simply "0"(zero). So, it is not null when Required attribute check it.

If you Prefer to use the Required attribute then replace your int to int? (Nullable int. The Default Value of Nullable int is null And can double-Check with it’s static .HasValue() method)

Or if you need to check that not pass the value when value is Zero or Less then you can use Range Attribute

Usage of Range Attribute :

[Range(1, Int32.MaxValue)]
public int Id {get;set;}

Simply you can change the Int32.MaxValue to your Maximum acceptable integer of your needs.

Hope this helps.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading