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に戻す場合、ブラウザはIndexへの全く新しいHTTP GET呼び出しを行います。したがって、TempDataを使用してエラーを転送する必要があります。モデルステート辞書は空になります(HTTPはステートレスです。以前の呼び出しが何であったかは分かりません)。 – Shyju
しかし、彼はすべてを保存してから、インデックスビューに戻したいだけです。言い換えれば、彼はこのコメント「//あなたのコードを保存して続ける」という意味を持っています。ここで彼は保存を行い、リダイレクトします。 – CodingYoshi