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

时间:2020-08-19 10:07:21

标签: asp.net-core asp.net-mvc-4 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方法触发,在其中添加带有userName的这本书类似内容,然后页面显示错误:

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”方法中填充的变量都为空...

请帮助:)

1 个答案:

答案 0 :(得分:2)

因为您不想重新加载页面并想要更新计数器。常见的方法是使用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; }
}

结果: enter image description here