Home > Software engineering >  Why does validation in ASP.NET Core Razor Pages doesn't accept empty inputs?
Why does validation in ASP.NET Core Razor Pages doesn't accept empty inputs?

Time:04-17

I am learning how to code in ASP.NET Core Razor Pages and am working on validation right now. Both in client side and server side validation no input is allowed to be empty even though I am not using the [Required] data annotation and I am looking for a solution to that. The C# code of the page is below:

    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }
        [BindProperty]
        public int number { get; set; }
        public void OnGet()
        {

        }
        public IActionResult OnPost()
        {
            if(!ModelState.IsValid)
            {
                return Page();
            }
            Console.WriteLine("It works.");
            return Page();
        }
    }

The HTML code of this page is below:

    <form method="post">
    <label asp-for="@Model.number">Number: </label><br />
    <input asp-for="@Model.number" />
    <span asp-validation-for="@Model.number" ></span>
    <br /><br />
    <button  type="submit">Submit</button>
</form>

    @section Scripts
{
}

Inside the Scripts section I use partial to load the Validation Scripts Partial. It just won't load there as code for some reason when I paste it there. It is only a simple code that is meant to take one integer from the user as I am just trying to get it to accept an empty value. I am using .NET 6.0 and Visual Studio Community Edition 2022. Does anyone know a solution to that problem? Thanks in advance.

CodePudding user response:

Because the int type does not accept null value, to solve your problem, change the code as follows To accept the amount of null as well

[BindProperty]
public int? number { get; set; }
  • Related