Search code examples
blazorblazor-server-sideblazor-editform

Problem when submitting EditForm when using using Parameter


I'm trying to have a Razor component that can function as the create and update page. When I am submitting a EditForm without passing a parameter in the route the submit function is called but when I pass a parameter and fill my editcontext with existing data the submit button just refreshes the page causing the OnInitializedAsync to be triggered again and my changes to be lost.

    public partial class PersonalInfo
    {
        private PersonalInfoModel _personalInfo = new PersonalInfoModel();
        private EditContext _editContext;
        private Response _customerResponse;

        [Parameter]
        public int? CustomerId { get; set; }

        [Inject]
        public CustomerService CustomerSvc { get; set; }
        [Inject]
        public NavigationManager NavManager { get; set; }

        protected override async Task OnInitializedAsync()
        {
            _editContext = new EditContext(_personalInfo);

            _customerResponse = await CustomerSvc.GetCustomer(CustomerId ?? 0);

            if (_customerResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                _personalInfo = _customerResponse.Content.Serialize().Deserialize<PersonalInfoModel>();
                _editContext = new EditContext(_personalInfo);
            }
        }

        private async Task Submit()
        {
            int customerId;
            if (_customerResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                customerId = await CustomerSvc.UpdateCustomer(_personalInfo);
            }
            else
            {
                customerId = await CustomerSvc.CreateCustomer(_personalInfo);
            }
     }

Razor Page

@page "/PersonalInfo/{CustomerId:int?}"
 <EditForm EditContext="_editContext" OnValidSubmit="@Submit">

 </EditForm>

Update:

I trimmed down the razor page to one field and not even a data annotation validator. It still has the same issue.

Razor Page


Solution

  • I faced a similar situation. For me, the OnInitializedAsync function was called twice due to pre-rendering. Once I disabled it, the form worked without an issue.