Search code examples
c#asp.net-coreasp.net-core-mvcextension-methodstempdata

Add extension method to TempData object in asp.net core


This piece of code shows how to set and then read the data from the TempData object:

TempData["ErrorMessage"] = "some message";
var foo = TempData["ErrorMessage"];

If I have to use very often the TempData["ErrorMessage"] in my app, there is always a risk of making a typo in the key when developing new stuff. I was thinking about a more secure way which would prevent this to happen, so I created a class:

/// <summary>
/// Contains a list of keys which are used in TempData across the controllers
/// </summary>
public static class TempDataKeys
{
    /// <summary>
    /// Stores the error message which is optionally dispalyed in the Shared/_ErrorMessage partial view defined in the _Layout.cshtml
    /// </summary>
    public const string ErrorMessage = "ErrorMessage";
}

and then set and read the data like this:

TempData[TempDataKeys.ErrorMessage] = "some message";
var foo = TempData[TempDataKeys.ErrorMessage];

Now I'm thinking if there is another way to achieve a similar thing by creation of an extension method for the TempData, so it would allow me to set and read the data like this

TempData.ErrorMessage = "some message";
var foo = TempDataKeys.ErrorMessage;

I know that it may look like the use of the ViewBag however, I need to have compile-time safety which ViewBag doesn't have. Anyway, the ViewBag works completely different from what I want to achieve.

Any ideas? Cheers


Solution

  • You could go down the path of Extension methods

    Looks quite neat:

    public static class Extension
    {
        public const string _ERROR = "ErrorMessage";
    
        public static void SetErrorMessage(this ITempDataDictionary @this, string message)
        {
            @this[_ERROR] = message;
        }
    
        public static string GetErrorMessage(this ITempDataDictionary @this) =>
            @this[_ERROR]?.ToString();
    }
    

    And then you can just get it like this var message = TempData.GetErrorMessage(); and you can set it using TempData.SetErrorMessage("Some Error");

    Similarly create Set/Update funcitons.

    I think another way you could achieve this is extend the Controller/PageModel, where you will be implementing your own TempData because I don't think you can override it. This could make the base class messy and you will essentially including alot of functionality in every single controller where you will use this base class and might be sharing functionality that you don't need.