Passing TempData with RedirectToAction

2020-06-09 04:33发布

Intro: I am a .NET studet trying to learn ASP.NET Core MVC. So please be understanding. I have searched the web for an answer to my problem, but havent found a solution that works for me.

Problem: I want to pass a validation message from my create post method to the index IActionmethod whenever a post has been created and them show it as an alert message for now. I have read on the web that ViewBag dosent survive a redirect, but a TempData does. This is my code so far.

Create post method:

 public IActionResult CreatePost(string textContent, string headline, string type)
    {

        var catType = new Category() { CategoryType = type.ToUpper() };

        if (db.Category.Any(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower()))
            catType = db.Category.FirstOrDefault(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower());


        var newPost = new Post()
        {
            Content = textContent,
            Header = headline,
            DateOfPost = DateTime.Now,
            category = catType

        };
        db.Posts.Add(newPost);
        db.SaveChanges();

        TempData["validation"] = "Your post hase been publsihed";

        return RedirectToAction("Index");
    }

The index method:

public IActionResult Index()
        {

        var validation = TempData["validation"];

            var posts = (from x in db.Posts
                         orderby x.DateOfPost descending
                         orderby x.PostID descending
                         select x);

            return View(posts);
        }

I have tried this guide: ClickThis and this one: ClickThis2 but I got this message:

ErrorPage

I know this line from gudie number 2 might be important, but didnt now how to apply it. -

var product = TempData["myTempData"] as Product;

The last thing I want to do is pass it to the index view, but dont know how. I am currently passing a model from the index.

Tell me if it is anything more you would like to see. Like dependencies.

All the help I get is gold and will be much appreciate!!!

5条回答
小情绪 Triste *
2楼-- · 2020-06-09 04:38

I'm just posting this for anyone who comes across this problem in an ASP.NET MVC application, @Ahmar's answer made me go look at my logout method, I was using Session.Abandon() before redirecting to the login page.

I just changed it to Session.Clear() to reset the session instead of removing it completely and now the TempData is working in the method I'm redirecting to.

查看更多
男人必须洒脱
3楼-- · 2020-06-09 04:39

Providers

The TempData is using various providers for storing the state. By default the cookie based data provider is used.

Session is just an alternative

If your application do not use session I do not see any reason to use it only for TempData store.

Cookie Consent

ASP NET Core 2.1 have some new GDPR features based on cookies. By default, data should be stored in cookies only with the user's consent. If the user does not agree with the storing data in cookies, TempData cannot work. This behavior varies across versions of ASP NET Core.

If you do not want to hold any sensitive data in cookies, you can obviously change the settings.

    app.UseCookiePolicy(new CookiePolicyOptions
    {
        CheckConsentNeeded = context => false
    });

You can set the CookiePolicyOptions separatelly in ConfigureServices as well. It is a quite cleaner.

Story continues

We have two kind of data in the cookies. Essential data (needed for running application) and non-essential (some user data). User consent is needed for non-essential data. TempData is non-essential. You can set you TempData as essential and user consent is not needed anymore:

services.Configure<CookieTempDataProviderOptions>(options => {
   options.Cookie.IsEssential = true;
});

I highly recommend to think about this before copy / paste.

查看更多
戒情不戒烟
4楼-- · 2020-06-09 04:54

TempData stores data server-side, under user Session. You need to enable sessions (as exception message says). Check this manual.

If you don't want to use sessions - you need some other way to store data (cookies?)

查看更多
来,给爷笑一个
5楼-- · 2020-06-09 04:55

Did you configure Session? TempData is using session behind the scenes.

Project.json

"Microsoft.AspNetCore.Session": "1.1.0"

Here is the Startup.cs file. - ConfigureServices method

public void ConfigureServices(IServiceCollection services)
{
     services.AddMemoryCache();
     services.AddSession();
     services.AddMvc();
}

And Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseSession();
    app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now try with TempData, it will work.

And you can set the environment with set ASPNETCORE_ENVIRONMENT=Development environment variable.

查看更多
唯我独甜
6楼-- · 2020-06-09 04:55

I landed on this question while googling for "asp.net core redirect to action tempdata". I found the answer and am posting it here for posterity.

Problem

My issue was that, after filling in some TempData values and calling RedirectToAction(), TempData would be empty on the page that I was redirecting to.

Solution

Per HamedH's answer here: If you are running ASP.NET Core 2.1, open your Startup.cs file and make sure that in your Configure() method app.UseCookiePolicy(); comes after app.UseMVC();.

Example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    app.UseCookiePolicy();
}
查看更多
登录 后发表回答