如何在OnGet()和OnPost()调用之间保留数据

时间:2019-03-30 13:42:12

标签: c# .net razor-pages

我正在开发的第一个Razor-pages应用程序让我有些困惑。

调用OnGet()函数时,将调用SpotifyAPI以获取当前用户的播放列表并将其分配给变量。然后需要在OnPost()调用中针对UI中的选定值检查此变量。

问题是,当调用OnPost()时,PlaylistsToLook变量现在为空。

是否可以在两次调用之间保留值?

这是cshtml.cs

public class CreateModel : PageModel
    {
        private readonly Models.AppDbContext _context;

        public CreateModel(Models.AppDbContext context)
        {
            _context = context;
        }

        public void OnGet()
        {
            PlaylistsToLook = PlaylistRequestService.GetUserPlaylists(_context);
        }

        public void OnPost(string[] playlistsToLook)
        {
            foreach (var playlistId in playlistsToLook)
            {
                PlaylistRequest.PlaylistsToLook.Add(PlaylistsToLook.First(x => x.id.Equals(playlistId)));
            }
            _context.PlaylistRequests.Add(PlaylistRequest);

            PlaylistRequestService.ProcessPlaylistRequest(PlaylistRequest, _context);
        }

        [BindProperty]
        public List<SpotifyPlaylist> PlaylistsToLook { get ; set; }

        [BindProperty]
        public Models.PlaylistRequest PlaylistRequest { get; set; }
    }

这是cshtml

@page
@model SpotifyPlaylistCurator.Pages.PlaylistRequest.CreateModel
@{
    ViewData["Title"] = "CreatePlaylist";
}

<h2>Create a Playlist</h2>
<form method="POST">
    <div class="form-group">
        <label asp-for="PlaylistRequest.Name" class="control-label"></label>
        <input asp-for="PlaylistRequest.Name" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="PlaylistRequest.Duration" class="control-label"></label>
        <input asp-for="PlaylistRequest.Duration" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="PlaylistRequest.PlaylistsToLook" class="control-label"></label>
        @{
        int cnt = 0;
            foreach (var playlist in Model.PlaylistsToLook)
            {
                if (cnt++ % 3 == 0)
                {
                    @:</tr><tr>
                }
                @:<td>
                    <input type="checkbox"
                           name="playlistsToLook"
                           value="@playlist.id" />
                            @playlist.name
                @:</td>
            }
        }
      </div>
    <div></div>
    <input type="submit" name="Create a Playlist" />
</form>

2 个答案:

答案 0 :(得分:0)

所以我创建了一个默认的Razor页面,以下是我为在Session中持久保存数据所做的更改

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        // ADD SESSION
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
        });
        // ADD MEMOERY CACHE
        services.AddMemoryCache();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //app.UseCookiePolicy(); I HAD TO COMMENT THIS LINE TO MAKE IT WORK

        // ADD USESESSION
        app.UseSession();
        app.UseMvc();
    }

在控制器中:

    public void OnGet()
    {
        var s = HttpContext.Session.GetString("MyData");
        if (!String.IsNullOrWhiteSpace(s))
        {

        }
        else
        {
            this.HttpContext.Session.SetString("MyData", "Test Data Here");
        }            
    }

    public void OnPost()
    {
        var s = HttpContext.Session.GetString("MyData");
        if (!String.IsNullOrWhiteSpace(s))
        {

        }
        else
        {
            this.HttpContext.Session.SetString("MyData", "Test Data Here");
        }
    }

这是一个非常简化的示例,但是您可以在以下位置阅读有关它的更多信息: Session State in Razor Pages

答案 1 :(得分:0)

PageModel的TempData属性应对此起作用。

默认情况下,基于cookie的版本是启用的,但是如果列表大于500bytes,则需要使用基于会话的版本:

public void ConfigureServices(IServiceCollection services)
{
    // snip

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddSessionStateTempDataProvider();

    services.AddSession();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // snip

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseSession();
    app.UseMvc();
}

来源: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#tempdata