Search code examples
.netblazor

What is the error of this Blazor EditForm?


I tried to follow the instruction of creating form from youtube channel like those: https://www.youtube.com/watch?v=zfqQ_fhmPOQ or https://www.youtube.com/watch?v=40njRXr6eUo or I even tried a very simple code like this

    <EditForm Model="@author" OnValidSubmit="SaveAuthor">
            <p>
                <label></label>
                <InputText id="FirstName" @bind-Value="author.FirstName"/>
            </p>
     </EditForm>

Here is my github link for the code sample https://github.com/maxrena/BlazorServerApp.git It still returns the error like this

InvalidOperationException: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.

Please help me with it.


Solution

  • This is the culprit:

    if ((EditContext == null) == (Model == null))
    {
        throw new InvalidOperationException($"{nameof(EditForm)} requires a {nameof(Model)} " +
            $"parameter, or an {nameof(EditContext)} parameter, but not both.");
    }
    

    You did not instantiate your model, and you do not have an EditContext

    You've probably did this: Author author;

    You should instantiate your object as done below:

    You can do something like this:

       @code {
           Author author = new Author();
           public class Author
           {
              public string FirstName {get; set;} = "Charls"; 
            }
       }
    

    Running sample:

        <EditForm Model="@author" OnValidSubmit="SaveAuthor">
        <p>
            <label></label>
            <InputText id="FirstName" @bind-Value="author.FirstName" />
        </p>
    
        <p><button type="submit">Submit</button></p>
    </EditForm>
    @code {
        Author author = new Author();
    
        private void SaveAuthor()
        {
            Console.WriteLine(author.FirstName);
        }
        public class Author
        {
            public string FirstName { get; set; } = "Charls";
        }
    }
    

    Hope this helps...