简体   繁体   English

ModelState.AddModelError 在 asp.net.core RAZOR 页面中不显示任何消息

[英]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.在我的测试 ASP.NET.CORE 项目中,我在我的 razor 代码隐藏页面中添加了一个 ModelState 自定义错误,但它对 Html.ValidationMessageFor 没有任何作用。 I have to redirect to OnGetAsync() method just not to recieve nullref exception我必须重定向到 OnGetAsync() 方法只是为了不接收 nullref 异常

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

When you redirect, you lose whatever is in the ModelState dictionary.当您重定向时,您将丢失ModelState字典中的任何内容。 If there is an exception you should return the same page, as you should if ModelState is not valid:如果出现异常,您应该返回相同的页面,就像ModelState无效时一样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过javascript提交表单后将ModelState.AddModelError添加到视图中 - Add ModelState.AddModelError to the view after submitting form through javascript 如何在尝试使用 Razor Pages 删除 ASP.NET Core 中的记录时显示确认消息 - How do I display a confirmation message with trying to delete a record in ASP.NET Core using Razor Pages 仅刷新 ASP.NET CORE Razor 页面中的内容页面 - Refresh only content page in ASP.NET CORE Razor Pages 如何在 CKEditor 5 中使用 asp.net core razor Pages 上传图片 - How upload image in CKEditor 5 With asp.net core razor Pages Asp .Net Core 2.2 Razor页面Ajax呼叫发布不起作用 - Asp .Net Core 2.2 Razor Pages Ajax Call Post not working 尝试在AlanJuden.MvcReportViewer中使用Find(Hightlight)-asp.net.core - Trying to use Find (Hightlight) in AlanJuden.MvcReportViewer - asp.net.core 将asp.net.core 2.0应用发布到IIS时JavaScript无法运行 - JavaScript not running when publishing my asp.net.core 2.0 app to IIS 你如何在 asp.net.core 中使用 Ajax 发布表单数据和文件? - How do you post form data and files using Ajax in asp.net.core? Razor 页面 ASP.NET 核心 - OnPost() 使用 datatables.net 搜索栏不返回任何对象 - Razor Pages ASP.NET Core - OnPost() using datatables.net search bar returns no objects 带有JQuery AJAX的.net核心Razor页面 - .net core Razor pages with JQuery AJAX
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM