What is the error of this Blazor EditForm?
Asked Answered
C

5

24

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.

Creak answered 11/6, 2020 at 7:20 Comment(2)
That is a very different error now. Add the code for that sets author.Ilanailangilang
Btw, you don't need the @ in front of author in this case, for example: <EditForm Model="author" OnValidSubmit="SaveAuthor">Bienne
E
42

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

Erase answered 11/6, 2020 at 8:29 Comment(7)
I had it in my code. Let me put my github link over here for you to see all the code github.com/maxrena/BlazorServerApp.gitCreak
I'm not sure I understand what you mean... Do you mean that your code is similar to mine, and still it does not work ? Did you post a link to your app so that I can look into the issue more closely. Please explain...Erase
I mean, I initiated author already, but in different way. I hope you can look into my code to tell me what makes the difference. Because I am learning this, I hope I can understand what is what.Creak
@maxrena, did you read my answer and understood my explanation ? I looked into your code. No you did not initiate or rather instantiate Author. You've just created a public property of the Author type, which initially returns the null value. I wouldn't recommend to use a property, though this is perfectly fine. Anyhow, doing the following solves the problem: public Author author { get; set; } = new Author(); which is equivalent to what I do in my answer above: Author author = new Author();Erase
In my answer the code under the title "This is the culprit:" is not mine. This code snippet is from the EditForm class definition. It checks whether the user had provided a Model object or the EditContext object (you can use EditContext instead of Model, depending on your design and needs). Now if your Model is null, which is because you do not instantiate it, and you've defined no EditContext, you get the exception InvalidOperationException (see the code above)...even the text message should by now be familiar to you.Erase
Please, don't hesitate to ask me any question if you're not sure what I'm talking about. Would you mind marking it as the answer if it solved your problem, so others know it was useful.Erase
God, thank you a lot, that's understandable and really helpful for a newbie like me.Creak
N
11

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>
``
Narbonne answered 6/1, 2021 at 18:6 Comment(3)
Correct - if part of your form is from an async operation you must check the data for null.Lyndel
I'm new to razor and omg thank you. I must do async Task loads of data and this saved my sanity.Groot
NOTE: If you have 2 or more objects that require instantiating within the OnInitializedAsync then you need to use an OR in the if statement above. i.e. @if (author== null || myOtherObject == null) { <p><em>Loading...</em></p> } else { ... show something ... }Lockridge
C
0

I had a very similar error. The error message said the same thing about an edit form which wasn't the page needing to be changed. The problem was the actual (Blazor) page causing the error kept trying to use a null object. Because I used the rest api, the page gave me the editform error because the rest api had to await data so it could instantiate the object. (The object is also a model by the way.) I resolved this in the page having the null object problem by using a conditional. If (object == null) return; So, when I did a debug trace, I found the code behind repeatedly going back to the OnInitializedAsync function and then to the page until the rest api returned and instantiated the page object. After the object was instantiated, the conditional in my page passed because the object was no longer null. The problem than was resolved.

Chilblain answered 24/1, 2024 at 17:52 Comment(0)
W
0

It's essential to understand how the EditForm works with Blazor SSR. In a previous version of Blazor, when you collected form data, you would typically put it into a model by binding it to the form. Then, you would send the model to the server as JSON, or if you were using Blazor Server, you could use the object directly in your code.

Either way, you weren't using the form data as actual form data.

Blazor SSR doesn't track the DOM in this way. Instead, like other Server-Side Rendered Technologies, it uses a Form Post to collect data and action on it. When your form is rendered in the browser, it has an action and method that tells the browser where to send the form when it's submitted.

Your form button, which is of type submit, no longer fires an action picked up in the browser and operated on by your code. Instead, the action fired is standard HTML, and the rules of HTML apply.

Clicking the Submit button tells the browser to gather the values from the Input Fields associated with your form. It then creates a Form-Data object that it sends back to the server to be processed. How does it know which inputs map to which fields?

Your browser uses the name attribute for this as the key for each piece of data sent back in the form-data array.

On the server side, your app needs to know how to use that data, and it does this using a nifty little attribute [SupplyParameterFromForm]. If you only have a single form, you can get away with not passing a name for the form to the attribute, but your form still needs a name for this to work. You set that name like so:

<EditForm Model="Input" method="post" OnValidSubmit="LoginUser" FormName="login">

FormName is Blazor SSR's identifier to map this form to a parameter. When there is more than one form, you'll need to specify which form the data is coming from in our attribute. You can do that like so:

[SupplyParameterFromForm(FormName="LoginUser")]

Now, all the pieces are in place, and when the browser sends your form to the server to be processed, Blazor SSR can map it to our property and run the associated code for submission. You can learn more about this by reading the following article:

https://www.johnnydevcraft.com/blazor-ssr-mudfields-editcontext-issues/

Wellhead answered 2/6, 2024 at 17:39 Comment(0)
F
0

If you are using MudBlazor for .NET 8 server-side rendering, the login page is statically rendered so there is no interactivity and MudBlazor and its UI Controls like MudTextField will not work as expected. A fix for this is either to use HTML5 controls e.g. (input) or the Blazor built-in controls e.g. (InputText). Note: If you change to HTML5 or built-in Blazor controls, the styling will be a bit off so you will have to use custom CSS to fix that.

Flagship answered 23/7, 2024 at 16:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.