【问题标题】:Display errors from ModelState.Values显示来自 ModelState.Values 的错误
【发布时间】:2016-12-30 19:08:38
【问题描述】:

我正在使用 ASP.net 核心剃须刀引擎。我试图在我的 html 中显示我的错误。不知道如何修复我的代码。如何显示来自的错误 ModelState.Values 在我的 cshtml 页面中?

这是我的控制器

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using quotingDojo.Models;

namespace quotingDojo.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        [HttpGet]
        [Route("")]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [Route("quotes")]
        public IActionResult Quotes(string Name, string Quote)
        {
            Home NewHome = new Home
            {
                Name = Name,
                Quote = Quote
            };

            if(TryValidateModel(NewHome) == false) {
                ViewBag.errors = ModelState.Values;
                System.Console.WriteLine("??????????????"); 
                System.Console.WriteLine(ModelState.ErrorCount);         
                System.Console.WriteLine("??????????????"); 
            }

            return RedirectToAction("Index");
        }
    }
}

ModelState.ErrorCount 打印出正确的错误数。

这是我的模型

using System.ComponentModel.DataAnnotations;


namespace quotingDojo.Models
{
    public class Home
    {
        [Required(ErrorMessage ="Please enter your name")]
        [Display(Name="*username")]
        [DataType(DataType.Text)]
        [MinLength(3)]
        public string Name {get; set;}

        [Required]
        [MinLength(5)]
        public string Quote{get; set;}
    }
}

这是我的cshtml页面

<div id="wrapper">  
    <h1>Welcome to the Quoting Dojo</h1>
    <form action="quotes" method="post">
        <p>
            <label>Your Name</label>
            <input type="text" name="Name"/>
        </p>
        <p>
            <label>Your Quote</label>
            <textarea name="Quote" id="quote" cols="30" rows="10"></textarea>
        </p>
        <input type="submit" name="submit" value="Add my quote!"/>
        <form action="quotes" method="get">
            <input type="submit" name="submit" value="Skip to quotes!"/>
        </form>
    </form>

 </div>

<div>
    <p> Test</p>
    @{
        if(ViewBag.errors != null)
        {
            foreach(var error in ViewBag.errors)
            {
                //If there are any errors for a field...
                if(@error.errors.Count > 0)
                {
                    // We show the first error for that field
                    <p>@error.errors[0].ErrorMessage</p>
                }
            }
        }

    }
</div>

我正在使用 Visual Studio Code,因此任何内容都构建到常规 Visual Studio 中,我没有访问权限。

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    使用 ViewBag 无需显式传递错误。当模型验证失败时,模型状态字典会出现错误。您所要做的就是在模型验证通过时执行您的代码。

    此外,由于您已经有一个类,您可以将它用作您的 http post 操作方法的参数。默认模型绑定器将能够将表单值映射到此类对象的属性。

    [HttpPost]
    [Route("quotes")]
    public IActionResult Quotes(Home model)
    {
      if(!ModelState.IsValid)
      {
        return View(model);
      }
      //continue your code to save
      return RedirectToAction("Index");
    }
    

    在视图中你可以使用验证辅助方法来显示验证错误

    @Html.ValidationSummary(false)
    

    另外,我注意到您在视图中有嵌套表单。嵌套表单不是有效的标记。所以我建议你也解决这个问题。

    <h1>Welcome to the Quoting Dojo</h1>
    @using(Html.BeginForm("Quote","Home"))
    {
        <p>@Html.ValidationSummary(false)</p>
        <p>
            <label>Your Name</label>
            @Html.TextBoxFor(s=>s.Name)
        </p>
        <p>
            <label>Your Quote</label>
            @Html.TextAreaFor(d=>d.Quote)
        </p>
        <input type="submit" name="submit" value="Add my quote!"/>
    
    }
    <form action="quotes" method="get">
        <input type="submit" name="submit" value="Skip to quotes!"/>
    </form>
    

    【讨论】:

    • 对不起!我的 if 条件错误 :( 请查看更新后的帖子
    • if 条件正确。如果模型状态有效,则返回视图,否则重定向到索引
    • 不!如果模型状态有效,继续保存然后重定向,如果模型状态无效,返回到我们将显示验证错误消息的同一视图
    • 知道了,现在我必须弄清楚如何让它们显示在 Index.cshtml 页面上
    【解决方案2】:

    显式模型验证 – 这是使用 IF..Else..IF 验证模型数据的传统方式 陈述。这样,您需要一一检查您的模型属性值以获得您想要的结果。 如果模型属性值是意外的,请在 ModelState 中注入错误消息。见下面的例子

    public class HomeController : Controller
    {
     [HttpPost]
      public ActionResult ExplicitServer(UserViewModel model)
         {
       //Write custom logic to validate UserViewModel
       if (string.IsNullOrEmpty(model.UserName))
       {
         ModelState.AddModelError("UserName", "Please enter your
      name");
     }
      if (!string.IsNullOrEmpty(model.UserName))
      {
        Regex emailRegex = new Regex(".+@.+\\..+");
         if (!emailRegex.IsMatch(model.UserName))
    
           ModelState.AddModelError("UserName", "Please enter correct
            email address");
       }
    
       if (ModelState.IsValid) //Check model state
      {
          //TO DO:
       }
      }
      }
    

    【讨论】:

    • 我知道这是一个旧答案,但是您将如何根据密钥在视图中显示错误?
    猜你喜欢
    • 2012-12-16
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多