为什么在MVC中RedirectToAction之后TempData[]为空

为什么在MVC中RedirectToAction之后TempData[]为空,redirect,model-view-controller,tempdata,Redirect,Model View Controller,Tempdata,问题:我在Post操作中设置了TempData,然后重定向到索引操作。在我设置TempData之后,它在post中不是NULL,但在Index操作中是NULL 我一直在寻找线索,以找到答案,我看到的一切都说,以下应该工作,但可惜,它没有 有人能看出这里出了什么问题吗 [HttpGet] public async Task<IActionResult> Index() { //var lCARContext = _context.

问题:我在Post操作中设置了TempData,然后重定向到索引操作。在我设置TempData之后,它在post中不是NULL,但在Index操作中是NULL

我一直在寻找线索,以找到答案,我看到的一切都说,以下应该工作,但可惜,它没有

有人能看出这里出了什么问题吗

[HttpGet]
        public async Task<IActionResult> Index()
        {
            //var lCARContext = _context.TblRules.Include(t => t.Agency).Include(t => t.Department);
            //return View(await lCARContext.ToListAsync());

            var rulevm = new RulesViewModel();
> TempData is NULL at this point.
            var actionConfirmation = TempData["ActionConfirmation"];
            TempData["ActionConfirmation"] = actionConfirmation;
            return View(rulevm);
        }

[HttpPost]
public async Task<IActionResult> Edit(string id, 
            [Bind("...")]
            TblRules tblRules, string NewProposedRuleNo)
        {
            if (id != tblRules.ProposedRuleNo)
            {
                return NotFound();
            }

            if (!tblRules.AgencyId.HasValue & !tblRules.DepartmentId.HasValue)
            {

                ModelState.AddModelError(string.Empty, "Select an Agency and/or Department for this rule.");
                // set the property level messages
                ModelState["AgencyId"].Errors.Add("Need either an Agency or Department specified.");
                ModelState["DepartmentId"].Errors.Add("Need either an Agency or Department specified.");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // first save any changes other than the rule number that the user
                    // has made.
                    _context.Update(tblRules);
                    await _context.SaveChangesAsync();

                    // Now if user changed the proposed rule number change it.
                    // Needs to be done outside of EF since EF does not support changing the PK.
                    if (NewProposedRuleNo != null)
                    {
                        _context.ChangeProposedRuleNumber(tblRules.ProposedRuleNo, NewProposedRuleNo);
                    }
                    // Return results of the action
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (!TblRulesExists(tblRules.ProposedRuleNo))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                TempData["ActionConfirmation"] = "Processing successful.";
> TempData is Not NULL at this point.
                return RedirectToAction("Index");
                //return RedirectToAction(nameof(Index));
            }
            // following executed if model is not valid
            ViewData["AgencyId"] = new SelectList(_context.TblAgencies.Where(wh => wh.AgencyOrBoard != null).OrderBy(ob => ob.AgencyOrBoard), "AgencyId", "AgencyOrBoard", tblRules.AgencyId);
            ViewData["DepartmentId"] = new SelectList(_context.TblDepartments.Where(wh => wh.DeptOrDivision != null).OrderBy(ob => ob.DeptOrDivision), "DepartmentId", "DeptOrDivision", tblRules.DepartmentId);
            ViewData["RuleType"] = new SelectList(_context.TlkpRuleTypes.OrderBy(ob => ob.RuleType), "RuleType", "RuleType", tblRules.RuleType);
            ViewData["Attorneys"] = new SelectList(_context.TblAttorneys.OrderBy(ob => ob.AttorneyName), "AttorneyName", "AttorneyName", null);
            ViewData["CurrentAttorneys"] = new SelectList(tblRules.TblReceivingAttorneys.OrderBy(ob => ob.AttorneyName), "AttorneyName", "AttorneyName", null);
            ViewData["CommitteesOfJurisdiction"] = new SelectList(_context.TblCommittees.OrderBy(ob => ob.CommitteName), "CommitteName", "CommitteName", null);
            ViewData["CurrentCommitteesOfJurisdiction"] = new SelectList(tblRules.TblCommitteesOfJurisdiction.OrderBy(ob => ob.CommitteName), "CommitteName", "CommitteName", null);
            ViewData["Actions"] = new SelectList(_context.TlkpActionsTaken.OrderBy(ob => ob.ActionDescription), "ActionDescription", "ActionDescription", null);
            ViewData["CurrentActions"] = new SelectList(tblRules.TblActions.OrderBy(ob => ob.ActionDescription), "ActionId", "ActionDescription", null);
            // Return the rules edit view model.
            var vm = tblRules.ToCreateRulesEditViewModel();
            // Return results of the action
            TempData["ActionConfirmation"] = "Validations failed.";
> TempData is Not NULL at this point AND is displayed on the view
            vm.AgencyContact = ViewModelExtensionMethods.FormatAgencyContactInformation(tblRules.Agency, true, true);
            return View(vm);
        }
[HttpGet]
公共异步任务索引()
{
//var lCARContext=_context.TblRules.Include(t=>t.Agency).Include(t=>t.Department);
//返回视图(等待lCARContext.toListSync());
var rulevm=new RulesViewModel();
>此时TempData为空。
var actionConfirmation=TempData[“actionConfirmation”];
TempData[“ActionConfirmation”]=ActionConfirmation;
返回视图(rulevm);
}
[HttpPost]
公共异步任务编辑(字符串id,
[绑定(“…”)]
TblRules TblRules,字符串新建议规则编号)
{
如果(id!=tblRules.ProposedRuleNo)
{
返回NotFound();
}
如果(!tblRules.AgencyId.HasValue&!tblRules.DepartmentId.HasValue)
{
AddModelError(string.Empty,“为此规则选择一个机构和/或部门”);
//设置属性级别的消息
ModelState[“AgencyId”].Errors.Add(“需要指定机构或部门”);
ModelState[“DepartmentId”].Errors.Add(“需要指定的机构或部门”);
}
if(ModelState.IsValid)
{
尝试
{
//首先保存除用户指定的规则编号以外的任何更改
//已经做了。
_上下文更新(tblRules);
wait_context.SaveChangesAsync();
//现在,如果用户更改了建议的规则编号,请更改它。
//需要在EF之外完成,因为EF不支持更改PK。
if(NewProposedRuleNo!=null)
{
_上下文.ChangeProposedRuleNumber(tblRules.ProposedRuleNo,NewProposedRuleNo);
}
//返回操作的结果
}
捕获(DbUpdateConcurrencyException ex)
{
如果(!TBLRulesSexists(tblRules.ProposedRuleNo))
{
返回NotFound();
}
其他的
{
投掷;
}
}
TempData[“操作确认”]=“处理成功。”;
>此时TempData不为NULL。
返回操作(“索引”);
//返回重定向到操作(名称(索引));
}
//如果模型无效,则执行以下操作
ViewData[“AgencyId”]=新的选择列表(_context.tblagences.Where(wh=>wh.AgencyOrBoard!=null).OrderBy(ob=>ob.AgencyOrBoard),“AgencyId”,“AgencyOrBoard”,tblRules.AgencyId);
ViewData[“DepartmentId”]=新选择列表(_context.TblDepartments.Where(wh=>wh.DeptOrDivision!=null)。OrderBy(ob=>ob.DeptOrDivision),“DepartmentId”,“DeptOrDivision”,tblRules.DepartmentId);
ViewData[“RuleType”]=新的选择列表(_context.tlkRuleTypes.OrderBy(ob=>ob.RuleType),“RuleType”,“RuleType”,tblRules.RuleType);
ViewData[“Attorneys”]=新的选择列表(_context.TblAttorneys.OrderBy(ob=>ob.AttorneyName),“AttorneyName”,“AttorneyName”,null);
ViewData[“CurrentAttorneys”]=新的选择列表(tblRules.TblReceivingAttorneys.OrderBy(ob=>ob.AttorneyName),“AttorneyName”,“AttorneyName”,null);
ViewData[“CommitteeSofJudiction”]=新的选择列表(_context.tblcommittes.OrderBy(ob=>ob.CommitteName),“CommitteName”,“CommitteName”,null);
ViewData[“CurrentCommitteeSofJudiction”]=新的选择列表(tblRules.TBLCommiteSofJudiction.OrderBy(ob=>ob.CommitteName),“CommitteName”,“CommitteName”,null);
ViewData[“Actions”]=新的SelectList(_context.tlkActionStaken.OrderBy(ob=>ob.ActionDescription),“ActionDescription”,“ActionDescription”,null);
ViewData[“CurrentActions”]=新的选择列表(tblRules.TblActions.OrderBy(ob=>ob.ActionDescription),“ActionId”,“ActionDescription”,null);
//返回规则编辑视图模型。
var vm=tblRules.ToCreateRulesEditViewModel();
//返回操作的结果
TempData[“操作确认”]=“验证失败。”;
>TempData此时不为NULL,并显示在视图上
vm.AgencyContact=ViewModelExtensionMethods.FormatAgencyContactInformation(tblRules.Agency,true,true);
返回视图(vm);
}
_Layout.cshtml,显示验证错误时的TempData,但不显示成功值

<div>
    @if (TempData["ActionConfirmation"] != null)
    {
        <p>@TempData["ActionConfirmation"]</p>
    }
    </div>

@if(TempData[“ActionConfirmation”]!=null)
{
@TempData[“操作确认”]

}
Index.cshtml,显示验证错误的临时数据,但不显示成功的临时数据

<div>
    @if (TempData["ActionConfirmation"] != null)
    {
        <p>@TempData["ActionConfirmation"]</p>
    }
</div>

@if(TempData[“ActionConfirmation”]!=null)
{
@TempData[“操作确认”]

}
我找到了解决方案。显然在Startup.Configure中,我需要将app.UserCookiePolicy()放在app.UseMVC()之后。进行此更改可以使Tempdata在整个重定向过程中保持不变

给了我解决问题的暗示。我依赖于hmdhasani的原始消息,而不是来自更深层次的示例,该示例仍然首先使用app.UserCookiePolicy

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

        app.UseCookiePolicy();
希望这篇文章能帮助别人