使用asp.net核心剃须刀。我目前的if语句是错误的,但这是获取错误消息的唯一方法。当前if语句是如果ModelState无效返回查看。在新视图上显示错误消息。但是,我想要的是,如果ModleState无效,重定向到Index.cshtml页面并显示错误。当我翻转if条件时,错误消息不会显示在Index.cshtml页面中。@ Html.ValidationSummary在错误页面上工作
这是我的控制器。
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(Home model)
{
if(!ModelState.IsValid)
{
return View();
}
//continue your code to save
return RedirectToAction("Index");
}
}
}
这里是我的Index.cshtml
@model quotingDojo.Models.Home
<h1>Welcome to the Quoting Dojo</h1>
@using(Html.BeginForm("Quotes","Home"))
{
<p>@Html.ValidationSummary()</p>
<p>
<label>Your Name</label>
@Html.TextBoxFor(s=>s.Name)
@Html.ValidationMessageFor(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>
这里是我的Quotes.cshtml其中的错误消息目前显示出来。
<h1>Test</h1>
<p>@Html.ValidationSummary()</p>
下面是使用System.ComponentModel.DataAnnotations我的模型页面 ;
namespace quotingDojo.Models
{
public class Home
{
[Required(ErrorMessage ="Please enter your name")]
[DataType(DataType.Text)]
[MinLength(3)]
public string Name {get; set;}
[Required]
[MinLength(5)]
public string Quote{get; set;}
}
}
他并不需要做到这一点。 MVC将从模型状态中选取错误。 – CodingYoshi
否。如果您要将RedrectResult返回给索引,您的浏览器正在对Index进行全新的HTTP GET调用。所以你需要使用TempData来传输错误。模型状态字典将是空的(HTTP是无状态的,它不知道以前的调用是什么) – Shyju
但他只会在保存完所有内容后才会这样做,然后他只想回到索引视图。换句话说,他有这样的评论:“//继续你的代码保存”,这意味着他将进行保存然后重定向。 – CodingYoshi