Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError doesn't show any message in asp.net.core RAZOR pages

In my test ASP.NET.CORE project I added a ModelState custom error in my razor codeBehind page but it's doing nothing for Html.ValidationMessageFor. I have to redirect to OnGetAsync() method just not to recieve nullref exception

So, I've tried replacing form from the popup modal but it does not help, connected scripts with layout partial view and directly to page don't give any result, renaming tags also.

This is my codeBehind of a Page

namespace TourStats.Pages
{
  public class Index : PageModel
  {
    private readonly TourStats.Models.PlayerStatsDBContext _context;
    public Index(TourStats.Models.PlayerStatsDBContext context)
    {
      _context = context;
    }

    [BindProperty]
    public Table Table { get; set; }
    [BindProperty]
    public IList<Table> Tables { get; set; }

    public async Task OnGetAsync()
    {
      Tables = await _context.Tables.ToListAsync();
    }

    public async Task<IActionResult> OnPostAsync()
    {
      if (ModelState.IsValid && Table != null)
     {
        try
          {
            Table.GameData = DateTime.Now;
            _context.Tables.Add(Table);
            await _context.SaveChangesAsync();
          }
          catch(Exception)
          {                 
            ModelState.AddModelError("Table", "exc1");                    
          }             
      }
        return RedirectToAction("OnGetAsync");                     
    }
  }
}

This is my Razor Page

@page
@using System.Runtime.CompilerServices
@using TourStats.Models
@model TourStats.Pages.Index
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers


@{
Layout = "_Layout";    
}

<head>
<!-- MY CSS -->
<link rel="stylesheet" type="text/css" href="~/css/playerPopup.css"/>
<!-- Validation Scripts -->
<script src="lib/jquery/dist/jquery.js"></script>
<script src="lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<title>MyStats</title>
</head>
<body>
<!-- Create Table Popup Form -->
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">create</button>

<div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">    
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <form method="post">
                        @Html.AntiForgeryToken()

                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <div class="form-group">
                            <label asp-for="Table.Name">Table name</label>
                            <input asp-for="Table.Name" class="form-control"/>
                            <span asp-validation-for="Table.Name" class="text-danger"></span>
                            @Html.ValidationMessageFor(m => m.Table)
                        </div>
                        <br>
                        <input type="submit" value="Create" class="btn btn-default"/>
                    </form>
                </div>
                <div class="modal-footer">

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

</div>

 @section Scripts{
    @await Html.PartialAsync("_ValidationScriptsPartial")
 }
like image 728
Evgeny Shmarev Avatar asked Oct 16 '22 07:10

Evgeny Shmarev


1 Answers

When you redirect, you lose whatever is in the ModelStatedictionary. If there is an exception you should return the same page, as you should if ModelState is not valid:

public async Task<IActionResult> OnPostAsync()
{
    if (ModelState.IsValid && Table != null)
    {
        try
        {
            Table.GameData = DateTime.Now;
            _context.Tables.Add(Table);
            await _context.SaveChangesAsync();
         }
         catch(Exception)
         {                 
             ModelState.AddModelError("Table", "exc1");  
             Tables = await _context.Tables.ToListAsync();
             return Page();                  
         }             
   } 
   else
   {
       Tables = await _context.Tables.ToListAsync();
       return Page(); 
   }
   return RedirectToAction("OnGetAsync");                     
 }
like image 199
Mike Brind Avatar answered Nov 02 '22 13:11

Mike Brind