LoginSignup
1
0

More than 1 year has passed since last update.

ASP .NET Core モデルの値をクリアしたい

Posted at

Createアクションの実行後、連続でCreateしたいため、Create後の画面遷移をreturn RedirectToAction(nameof(Index));でなく、return View();でからっぽのモデルをセットして、同じCreateに戻したい時がある。
その際に、ついでに、登録完了のメッセージを出したい。
しかし、単純にreturn View(model);で値をセットしても、ModelStateに状態を持っているため、画面側は更新されない。
ModelState.Remove("列名")でプロパティの値を、ModelState.Clear()でモデルのエラーがクリアされる。
それらを考慮して、以下のような感じで作った

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Feedback")] UsersFeedback usersFeedback)
        {
            if (ModelState.IsValid)
            {
                usersFeedback.CreatedAt = DateTime.Now;
                _context.Add(usersFeedback);
                await _context.SaveChangesAsync();
                ModelState.AddModelError("", $"ご意見・ご要望ありがとうございました。"); //メッセージをValidationErrorのところに表示
                ModelState.Remove("Feedback"); //消したい属性
                return View();
            }
            return View(usersFeedback);
        }

元ネタ:
ModelState.Clear() is required to display back your model object
https://patrickdesjardins.com/blog/modelstate-clear-is-required-to-display-back-your-model-object

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0