【发布时间】: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