skip to Main Content

I’m pretty new to Blazor and I’m working on this little webapp which just logs form data into a JSON file (code below). However, the values for tmp.Cname and Cdate remain null when I submit the EditForm. Did I not use Model or bind-Value correctly? Thanks!!

@using System.Text.Json;
@page "/"

@code {
    LogObject tmp = new LogObject();
   
    public class LogObject{
        public string Date {get; set;}
        public string CDate {get; set;}
        public string CName {get; set;}
    }

    public void OnSubmit(){
        Console.WriteLine(tmp.CName + " at " + tmp.CDate);
    }
}

<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>

<EditForm Model="tmp" OnSubmit = "OnSubmit" FormName="sample">
    <InputText @bind-Value="tmp.CName" /><br />
    <InputText @bind-Value="tmp.CDate" /><br />
    <button type="submit">Submit</button>
</EditForm>

<p>@tmp.CName changed at @tmp.CDate logged at @tmp.Date</p>

2

Answers


  1. Depending on the render mode that you’re using, you may need a [SupplyParameterFromForm] attribute on your model…

    [SupplyParameterFromForm(FormName = "sample")]
    LogObject tmp = new LogObject();
    
    Login or Signup to reply.
  2. According to your description, it seems you are using the Blazor web app 8, if you are not set the render mode, it will use the static server render mode by default.

    By using this mode, it will work as static content which will not modify the page after you click the submit button, it is not Interactive.

    To solve this issue, you need set the render mode for it, you could set it as InteractiveServer, then you could find it works well.

    More details, you could refer to below example and this article:

    Add this line: @rendermode InteractiveServer

    @page "/"
    @rendermode InteractiveServer
    
    @code {
        LogObject tmp = new LogObject();
    
        public class LogObject
        {
            public string Date { get; set; }
            public string CDate { get; set; }
            public string CName { get; set; }
        }
    
        public void OnSubmit()
        {
            Console.WriteLine(tmp.CName + " at " + tmp.CDate);
        }
    }
    
    <PageTitle>Home</PageTitle>
    <h1>Hello, world!</h1>
    
    <EditForm Model="tmp" OnSubmit="OnSubmit" FormName="sample">
        <InputText @bind-Value="tmp.CName" /><br />
        <InputText @bind-Value="tmp.CDate" /><br />
        <button type="submit">Submit</button>
    </EditForm>
    
    <p>@tmp.CName changed at @tmp.CDate logged at @tmp.Date</p>
    

    Result:

    enter image description here

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search