How to use the TempData attribute to pass data to a Razor view

Viewed 473

I have:

namespace Test
{
    public interface ITest
    {
        public string Test1(string s);
    }

    public class Test : ITest   
    {
        [Microsoft.AspNetCore.Mvc.TempData]
        public string Message
        {
            get; set;
        }
        public string Test1(string s)
        {
            Message = "Test " + s;
            return "Test has run";
        }
    }
}

And in Startup.cs:

services.AddScoped<Test.ITest, Test.Test>();

Then in a Razor view:

@inject Test.ITest Test

<p>Result is @Test.Test1("Hello World!")</p>
<p>TempData["Message"] is @TempData["Message"]</p>

The output is:

Result is Test has run

TempData["Message"] is

Where have I done incorrectly? How can I pass a TempData["Message"] from some code (that is not in a Controller) to a Razor page?

1 Answers

How can I pass a TempData["Message"] from some code (that is not in a Controller) to a Razor page?

If you'd like to retain and pass value via TempData inside your custom service, you can try the following code snippet.

public interface ITest
{
    public string Test1(string s);
    public string Test2();
}

public class Test : ITest
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public Test(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string Message
    {
        get {
            var tempDataDictionaryFactory = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<ITempDataDictionaryFactory>();
            var tempDataDictionary = tempDataDictionaryFactory.GetTempData(_httpContextAccessor.HttpContext);
            if (tempDataDictionary.TryGetValue("Message", out object value))
            {
                return (string)value;
            };

            return "";
        }
        set
        {
            var tempDataDictionaryFactory = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<ITempDataDictionaryFactory>();
            var tempDataDictionary = tempDataDictionaryFactory.GetTempData(_httpContextAccessor.HttpContext);
            tempDataDictionary.Remove("Message");
            tempDataDictionary.TryAdd("Message", value);
        }
    }
    public string Test1(string s)
    {
        Message = "Test " + s;
        return "Test has run";
    }

    public string Test2()
    {
        return Message;
    }
}

In Razor Page

<p>Result is @Test.Test1("Hello World!")</p>
<p>TempData["Message"] is  @TempData.Peek("Message")</p>

<p>@Test.Test2()</p>

Test Result

enter image description here

Related