0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【ASP.NET Core6.0】bool値の入力フォームでhiddenの値が自動生成されて困った話

Last updated at Posted at 2023-02-05

環境

ASP.NET Core 6.0

問題

bool値の入力フォームを作ると、勝手にhiddenの値がformタグ終了直前に出力される。

ExampleEntity.cs
// エンティティ
public class ExampleEntity
{
    public bool IsDeleted { get; set; }
}
form.cshtml
<form method="post">
    <input asp-for="@Model.IsDeleted">
    <!-- 他 -->
    <!-- の -->
    <!-- コ -->
    <!-- | -->
    <!-- ド -->
</form>

// ↓↓↓↓↓ 実際出力されるHTML ↓↓↓↓↓
<form method="post">
    <input name="IsDeleted" type="checkbox" value="false" />
    <!-- 他 -->
    <!-- の -->
    <!-- コ -->
    <!-- | -->
    <!-- ド -->
    <input name="IsDeleted" type="hidden" value="false" />  // ← これがいらない
</form>

解決方法

Program.csに下記を追記する

Program.cs
services.Configure<MvcViewOptions>(options =>
    options.HtmlHelperOptions.CheckBoxHiddenInputRenderMode =
        CheckBoxHiddenInputRenderMode.None);

参考

ASP.NET Core のフォームのタグ ヘルパー

あとがき

複数のEntityを更新・追加・削除できる画面を作成時に何故かbool値のあるフォームのみ下記のような現象が起きました。

① Entityを追加ボタンを押下(Ajaxで入力フォームを取得)
② ①の入力フォームを未入力のまま、更新ボタンを押下
③ 入力エラー画面が表示される
④ ①で追加した空のEntityの削除ボタンを押下
 (DBには登録されていないので①で追加されたHTMLをJSで削除)
④ 更新ボタンを押下すると、削除したはずのEntityが追加された状態でまたエラー画面が表示される

原因は上記の通り、formの最後にhiddenが追加されおり、その値がPOSTされたため、削除したと思っていたEntityが削除できておらず・・・。
bool値がないEntityはできてるのに、このEntityだけなんでこうなるのさとはまったので記録として残しておきます。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?