我想将通知保存在TempData
中并向用户显示。我为此创建了扩展方法并实现了从ActionResult
扩展的类。我需要访问TempData
方法ActionContext
。在ExecuteResult中访问TempData Asp.Net MVC Core
扩展方法:
public static IActionResult WithSuccess(this ActionResult result, string message)
{
return new AlertDecoratorResult(result, "alert-success", message);
}
扩展的ActionResult类。从控制器
return RedirectToAction("Index").WithSuccess("Category Created!");
public class AlertDecoratorResult : ActionResult
{
public ActionResult InnerResult { get; set; }
public string AlertClass { get; set; }
public string Message { get; set; }
public AlertDecoratorResult(ActionResult innerResult, string alertClass, string message)
{
InnerResult = innerResult;
AlertClass = alertClass;
Message = message;
}
public override void ExecuteResult(ActionContext context)
{
ITempDataDictionary tempData = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionary)) as ITempDataDictionary;
var alerts = tempData.GetAlert();
alerts.Add(new Alert(AlertClass, Message));
InnerResult.ExecuteResult(context);
}
}
调用扩展方法我得到 'TempData的' 空,我如何才能获得 'TempData的' IN '的ExecuteReuslt' 的方法。
是的,我们看相同的课程。我调用了ExecuteResult,但它没有在TempData中保留警报。我尝试了异步方法,但问题仍然存在。警报并没有持续存在,也没有显示出来。你有能力做到这一点吗? – Ahmar
(对不起,关于延迟,新的一年来临之间:-)是的,它适用于我,我可以在我的视图中访问TempData.GetAlerts,并从那里获取数据...不知道可能会有什么不同: - /我必须启用会话,其中涉及添加nuget包“Microsoft.AspNetCore.Session”和“Microsoft.Extensions.Caching.Memory”,然后添加“services.AddMemoryCache(); services.AddSession();”在Startup.cs中的ConfigureServices方法中。和“app.UseSession();”在Configure方法中。 –
我在做同样的事情,但是当在视图中访问TempData时,它总是空的? – Cocowalla