What is the error of this Blazor EditForm?

Viewed 14610

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 Please help me with it.

2 Answers

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

To enable the server load data without firing an exception, you can use the next code:

@if (author== null)
{
    <p><em>Loading...</em></p>
}
else
{
  <EditForm Model="@author">
  ....
</EditForm>
``
Related