Blazor EditForm の送信ボタンをコンポーネントの外側に配置する方法 質問する

Blazor EditForm の送信ボタンをコンポーネントの外側に配置する方法 質問する

Blazorのドキュメントのフォーム検証の例コンポーネント内に送信ボタン コンポーネントがありますEditForm

    <EditForm Model="@starship" > OnValidSubmit="@HandleValidSubmit">
        <DataAnnotationsValidator />
        <ValidationSummary />
    
        <p>
            <label for="identifier">Identifier: </label>
            <InputText id="identifier" bind Value="@starship.Identifier" />
        </p>
    
        Snip....

        <button type="submit">Submit</button>

        Snip...

    </EditForm>

送信ボタンを配置する方法はありますか?タグのJavaScript を使用せずに、EditFormそのコンポーネントの送信を「ネイティブに」トリガーすることはできますか?EditForm

つまり、コードは次のようになります。

    <!-- Want this button to submit the form in the EditForm tags-->
    <button type="submit">Submit</button>

    Snip...

    <EditForm Model="@starship" OnValidSubmit="@HandleValidSubmit">
        <DataAnnotationsValidator />
        <ValidationSummary />
    
        <p>
            <label for="identifier">Identifier: </label>
            <InputText id="identifier" bind-Value="@starship.Identifier" />
        </p>
    </EditForm>

ベストアンサー1

とても簡単です:

  • id属性を追加するEditForm
  • 送信ボタンを の外側に配置しEditForm、そのform属性に の IDを割り当てますEditForm

実際に動作するコードサンプルは次のとおりです。

    @using System.ComponentModel.DataAnnotations;    

    <EditForm id="@MyID" Model="Model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label for="name">Name: </label>
        <InputText Id="name" Class="form-control" @bind-Value="@Model.Name"> 
        </InputText>
        <ValidationMessage For="@(() => Model.Name)" />

    </div>
    <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind-Value="@Model.Text"> 
        </InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
    </div>
    </EditForm>

    <p>
        <button type="submit" form="@MyID" class="btn btn-primary">Save</button>
        <button type="button" class="btn btn-light" 
                               @onclick="@Cancel">Cancel</button>
    </p>
    @code
    {
        private string MyID = "myid";

        private Comment Model = new Comment();

        public async Task HandleValidSubmit()
        {
            //  await Task.Delay(3000);

            await Task.Run(() =>
            {
                Console.WriteLine("Saving...");
                Console.WriteLine(Model.Name);
                Console.WriteLine(Model.Text);
            });

        }

        private void Cancel()
        {
            Console.WriteLine("Cancelling...");
            Console.WriteLine(Model.Name);
            Console.WriteLine(Model.Text);
        }

       public class Comment
       {
           [Required]
           [MaxLength(10)]
           public string Name { get; set; }

           [Required]
           public string Text { get; set; }

       }

    }

お役に立てれば...

おすすめ記事