最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ModelState.AddModelError doesn't show any message in asp.net.core RAZOR pages - Stack Overflow

programmeradmin3浏览0评论

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")
 }

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")
 }
Share Improve this question asked Jan 23, 2019 at 10:12 Evgeny ShmarevEvgeny Shmarev 631 silver badge5 bronze badges 1
  • You should use core way of doing things, instead of old 4.5 style. So use tag helpers instead of html helpers and ValidateAntiForgeryToken attribute on the right PageModel or controller action. – Vlad Radu Commented Jul 9, 2019 at 7:36
Add a ment  | 

1 Answer 1

Reset to default 4

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");                     
 }
发布评论

评论列表(0)

  1. 暂无评论