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.
The EditForm component is Blazor's approach to managing user-input in a way that makes it easy to perform validation against user input. It also provides the ability to check if all validation rules have been satisfied, and present the user with validation errors if they have not.
When rendering an EditForm component, Blazor will output an HTML <form> element. As this is a standard web control, we can provide the user with the ability to submit the form by adding an <input> with type="submit" . Blazor will intercept form submission events and route them back through to our razor view.
You have to define and bind the EditContext with EditForm and then call the method editContext. Validate() on button click to manually trigger the validation.
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>
``
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With