使用 RedirectToAction 传递 TempData [英] Passing TempData with RedirectToAction

查看:24
本文介绍了使用 RedirectToAction 传递 TempData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:我是一名尝试学习 ASP.NET Core MVC 的 .NET 学生.所以请谅解.我在网上搜索了我的问题的答案,但还没有找到适合我的解决方案.

问题:每当创建帖子时,我想将验证消息从我的 create post 方法传递给索引 IActionmethod,并且它们现在将其显示为警报消息.我在网上读到 ViewBag 不会在重定向中幸存,但 TempData 可以.这是我目前的代码.

创建发布方法:

 public IActionResult CreatePost(string textContent, string header, 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(){内容 = 文本内容,标题=标题,DateOfPost = DateTime.Now,类别 = catType};db.Posts.Add(newPost);db.SaveChanges();TempData["validation"] = "您的帖子已发布";return RedirectToAction("索引");}

索引方法:

public IActionResult Index(){var 验证 = TempData["验证"];var posts =(来自 db.Posts 中的 xorderby x.DateOfPost 降序orderby x.PostID 降序选择 x);返回视图(帖子);}

我已经尝试过这个指南:

我知道来自 gudie 2 号的这条线可能很重要,但现在不知道如何应用它.-

<块引用>

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

我想做的最后一件事是将它传递给索引视图,但不知道如何.我目前正在从索引中传递一个模型.

如果您还想看什么,请告诉我.像依赖一样.

我得到的所有帮助都是金子,将不胜感激!!!

解决方案

你配置了Session吗?TempData 在幕后使用会话.

项目.json

"Microsoft.AspNetCore.Session": "1.1.0"

这是 Startup.cs 文件.- ConfigureServices 方法

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

配置方法.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){应用程序.UseSession();app.UseMvc(路由 => {路线.MapRoute(名称:默认",模板:{controller=Home}/{action=Index}/{id?}");});}

现在尝试使用 TempData,它会起作用.

您可以使用 set ASPNETCORE_ENVIRONMENT=Development 环境变量来设置环境.

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:

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

解决方案

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.

这篇关于使用 RedirectToAction 传递 TempData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆