在剃刀页面中变量的 OnPost 值重置为 null 之后

after OnPost values of variables reset to null in razor pages

我想在我的页面上添加简单的点赞功能(仅显示数据)。

我的页面后面有 PageModel 中的方法(这只是示例,因为我的页面太复杂了):

(..)getting DB context and stuff
public string bookName {get;set;}
public string someVariable1 {get;set;}
public List<string> _bookTags {get;set;}
public int LikeCounter {get;set;}

public void OnGet(){
      someVariable1 = (from u in _context.table
                       where something==something
                       select u.x);
          _bookTags= (from u in _context.bookTags
                       where something==something
                       select u.y).ToList();
      LikeCounter = (from u in _context.likes
                       where u.book==bookName 
                       select u).Count();
}

public void OnPost(){
      likes newLike = new likes();
      newLike.userName = HttpContext.User.Identity.Name.Split("\")[1];
      newLike.book = bookName;
      _context.likes.add(newLike);
      _context.SaveChanges();
}

页面如下所示:

(..)
<div class="col-lg-4">
        <form method="post">
            <button class="btn btn-reddit" type="submit">LikeThisBook</button>
        </form>
        Current likes: @Model.LikeCounter 
</div>
(..)
@foreach(string x in Model._bookTags){
        <div class="border">
          @x
        </div>
}
(..)

所以问题是当我显示页面时 - 一切正常,但是当我单击“LikeThisBook”时 - OnPost 方法触发,为这本书添加用户名的喜欢...然后页面显示错误:

ArgumentNullException: Value cannot be null. (Parameter 'source')

并在堆栈跟踪中:

SomeProjectName.Pages.SomeBookStore.Pages_SomeBookStore_ShowBook.ExecuteAsync() in ShowBook.cshtml
@foreach(string x in Model._bookTags){    <- this is colored red

所以看起来在“OnGet”方法中填充的每个变量现在都是空的...

请帮忙:)

如果您不想重新加载页面并希望更新 counter.The,常用方法是使用 ajax。

这是一个工作演示:

Index.cshtml:

@page
@model IndexModel
<div class="col-lg-4">
    <form method="post">
        <input name="bookName" />
        <button type="button" class="btn btn-reddit" onclick="Add()">LikeThisBook</button>
    </form>
    Current likes: <label>@Model.LikeCounter</label>   @*add this*@
</div>
@foreach (string x in Model._bookTags)
{
    <div class="border">
        @x
    </div>
}
@section Scripts
{ 
    <script>
        function Add() {
            $.ajax({
                type: "post",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                success: function (data) {
                    $("label").html(data);
                },
                error: function () {
                    alert("Fail to add");
                }
            });
        }
    </script>
}

Index.cshtml.cs:

public class IndexModel : PageModel
{
    private readonly RazorProj3_1Context _context;

    public IndexModel(RazorProj3_1Context context)
    {
        _context = context;
       
    }
    [BindProperty]
    public string bookName { get; set; }
    public string someVariable1 { get; set; }
    public List<string> _bookTags { get; set; }
    public int LikeCounter { get; set; }

    public void OnGet()
    {
        someVariable1 = (from u in _context.table
                         where u.Id == 1
                         select u.x).FirstOrDefault();
        _bookTags = (from u in _context.bookTags
                     select u.y).ToList();
        LikeCounter = (from u in _context.likes
                           //where u.book == bookName
                       select u).Count();
    }

    public ActionResult OnPost()
    {
        like newLike = new like();
        newLike.book = bookName;
        _context.likes.Add(newLike);
        _context.SaveChanges();
        LikeCounter = (from u in _context.likes
                           //where u.book == bookName
                       select u).Count();
        return new JsonResult(LikeCounter);
    }
}

Startup.cs:

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

我的测试模型:

public class likes
{
    public int Id { get; set; }
    public string book { get; set; }
}
public class BookTag
{
    public int Id { get; set; }
    public string y { get; set; }
}
public class Table
{
    public int Id { get; set; }
    public string x { get; set; }
}

结果: