Razor Pages에 양식 게시

작동시키기 위해 조금 고생했습니다.
행복하게 읽었습니다 Sending an anti-forgery token with Razor Pages AJAX requests , 모든 것이 명확해졌습니다 :-)

주요 양식은 다음과 같습니다.

 <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>

그리고 C# 부분

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
      };
    }
  }
}

좋은 웹페이지 즐겨찾기