DEV Community

artydev
artydev

Posted on

Posting forms in Razor Pages

I have been struggling a little in order to get it working.
Happily I read Sending an anti-forgery token with Razor Pages AJAX requests, and all became clear :-)

Here is the main form :

 <div style="width:500px; margin:0 auto;margin-top: 150px; ">
  <h2 style="text-align:center;">Posting form in Razor Page</h2>

  <form method="post" id="userform" asp-antiforgery="true">
    <div class="form-group">
      <label asp-for="UserInfo.FirstName"></label>
      <input asp-for="UserInfo.FirstName" name="FirstName"  class="form-control">
    </div>
    <div class="form-group" anti>
      <label asp-for="UserInfo.LastName"></label>
      <input asp-for="UserInfo.LastName" name="LastName" class="form-control">
    </div>
    <button type="submit" class="btn btn-primary">Add User</button>
    <input name="__RequestVerificationToken" type="hidden" 
        value='@AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'>
  </form>
</div>

<script>   
    userform.addEventListener('submit', function (e) {
      e.preventDefault();
      const postUrl = '@LinkGenerator.GetUriByPage(HttpContext, handler: "UserInfo")';
      const formData = new FormData(this);
      new Response(formData).text().then(console.log)
      fetch(postUrl, {
        method: 'post',
        body: formData
      }).then(function (response) {
        alert("data posted")
        console.log(response);
      });
    })
</script>

and the c# part

namespace PublicProject
{
  public class UserInformation
  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
  }
  public class indexModel : PageModel
  {
    [BindProperty]
    public UserInformation UserInfo { get; set; }

    public void OnGet()
    {
    }

    public void OnPostUserInfo()
    {
      var user = new UserInformation
      {
        FirstName = UserInfo.FirstName,
        LastName = UserInfo.LastName
      };
    }
  }
}

Top comments (0)