Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

DataAnnotations Validation not working properly in ASP.NET Core 2.0 Razor Pages.

$
0
0

Hi All,

I have created a new ASP.NET Core 2.0 Razor Pages application. Everything is working butfor some unknown reason, it doesn't show the custom validation messages instead it shows some default validations. The screen shot is below. Does anyone know what is the problem?

The code is below.

Model

    public class MathsCalc
    {
        [Required(ErrorMessage = "First Number is required.")]
        public decimal FirstNumber { get; set; }

        [Required(ErrorMessage = "Second Number is required.")]
        public decimal SecondNumber { get; set; }

        public decimal Result { get; set; }
    }

PageModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebApplication18.Models;

namespace WebApplication18.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public MathsCalc MathsCalc { get; set; }

        public void OnGet()
        {
            if (MathsCalc == null)
            {
                MathsCalc = new MathsCalc();
            }

            Page();
        }

        public void OnPost()
        {
            if (ModelState.IsValid)
            {
                MathsCalc.Result = MathsCalc.FirstNumber + MathsCalc.SecondNumber;
            }

            Page();
        }
    }
}

Razor Page

@page
@model IndexModel<h2>Simple Calculation In Razor Pages</h2><form method="post"><div asp-validation-summary="All"></div><div><div><label asp-for="@Model.MathsCalc.FirstNumber"></label><input asp-for="@Model.MathsCalc.FirstNumber" /><span asp-validation-for="@Model.MathsCalc.FirstNumber"></span></div></div><div><div><label asp-for="@Model.MathsCalc.SecondNumber"></label><input asp-for="@Model.MathsCalc.SecondNumber" /><span asp-validation-for="@Model.MathsCalc.SecondNumber"></span></div></div><div><button type="submit">Show Result</button></div><div><label>Result: @Model.MathsCalc.Result</label></div></form>

Thanks in advance.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>