Html.BeginForm in Blazor

Viewed 212

When working with MVC you can use

@using (Html.Beginform("", ""))
{
@Html.ValidationSummary("true")
}

To show an error message from the controller.

In one of my controllers I have this code

Game existingGame = context.Games.FirstOrDefault(g => g.Title == game.Title.ToLower());
                if(existingGame != null)
                {
                    ModelState.AddModelError(string.Empty, "This Game already exist");
                }
                else if(ModelState.IsValid)
                {
                    context.Add(game);
                    await context.SaveChangesAsync();
                    return game.Id;
                }
                return Ok();  

This code work, cause I cant add a second game with the same name. But how do I display the error message in a razor-component with blazor?

I tried the Html.Beginform but I got an error.

1 Answers

In Blazor, the equivalent of

@Using(Html.BeginForm())
{
    @Html.ValidationSummary("true")
}

would be

<EditForm Model=@MyModel>
   <ValidationSummary />
</EditForm>

If you're just moving to Blazor, I highly recommend going through the tutorials at: https://blazor-university.com/forms/ for advice specific to forms.

And check out the other tutorials at that site.

Related