Search code examples
c#asp.net-corerazor-pages

Razor form submitting only a single input field


I am creating a simple form in Razor Page, it's sending the form values back to frontend but when I use the same values at backend they are null.

Frontend Backend

    <form method="POST" class="form form--login">
      <fieldset class="card card--login">
        <legend>Login</legend>

        <input aria-label="username" name="Username" type="text" title="Username can't be empty." placeholder="Username"
        class="input input--text" />

        <input aria-label="password" name="Password" type="password" title="Password is required." placeholder="Password"
        class="input input--text" />

        <input aria-label="Test" name="Test" type="datetime-local" title="Test is required." placeholder="Test"
        class="input input--text" />
      </fieldset>

      <button type="submit" class="button button--submit">Submit</button>
    </form>


@* Using this to check for values after form submission *@
@Model.Username
@Model.Password
@Model.Test
    public string Username { get; set; }
    public string Password { get; set; }
    public string Test { get; set; }

    Username = Request.Form["Username"];
    Password = Request.Form["Password"];
    Test = Request.Form["Test"];

    Console.WriteLine(Username, Password, Test);

Solution

  • Edit your PageModel like following:

     public class IndexModel : PageModel
    {
      
        [BindProperty]
        public string Username { get; set; }
        [BindProperty]
        public string Password { get; set; }
        [BindProperty]
        public string Test { get; set; }
    
        public void OnGet()
        {
        }
        public IActionResult OnPost()
        {
    
            return Page();
        }
    }
    

    Your page:

    @page
    @model IndexModel
    
    <form method="POST" class="form form--login">
        <fieldset class="card card--login">
            <legend>Login</legend>
    
            <input aria-label="username" name="Username" type="text" title="Username can't be empty." placeholder="Username"
                   class="input input--text" />
    
            <input aria-label="password" name="Password" type="password" title="Password is required." placeholder="Password"
                   class="input input--text" />
    
            <input aria-label="Test" name="Test" type="datetime-local" title="Test is required." placeholder="Test"
                   class="input input--text" />
        </fieldset>
    
        <button type="submit" class="button button--submit">Submit</button>
    </form>
    @Model.Username
    @Model.Password
    @Model.Test
    

    Test Result:

    enter image description here

    For more details,you can learn this article.