How to place submit button for a Blazor EditForm outside of the component

前端 未结 1 980
感动是毒
感动是毒 2020-12-31 15:23

The Blazor documentation\'s Form Validation example has a submit button component within the EditForm component:



        
相关标签:
1条回答
  • 2020-12-31 16:12

    It's very simple:

    • Add an id attribute to the EditForm
    • Put the submit button outside the EditForm, and assign to its form attribute the id of the EditForm.

    Here's a working code sample:

        @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; }
    
           }
    
        }
    

    Hope this helps...

    0 讨论(0)
提交回复
热议问题