Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C# 5.0
Tip/Trick

Using TempData Outside the Controller in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.86/5 (3 votes)
1 Jun 2014CPOL1 min read 26.4K   7   1
Using TempData outside the controller in ASP.NET MVC and making TempData less prone to error and more intuitive.

What is the Problem We Are Trying to Fix?

When you start using Tempdata, it quickly becomes evident that maintaining it will be quite a challenge because Intellisense doesn't support Tempdata since it's a Dictionary. Without intellisense, suddenly life looks gloomy, but no fear. There is hope!

My Problem

The problem raised when I wanted to use Notification Object across my website. I wanted to throw this object from one controller to the other (tempdata job) and finally send it to the view. If I wanted to use TempData["something"], then I have to remember this "something".

So instead of hardcoding this "something" inside the controller, I decided to put the hardcoding inside a Helper.cs function and simply call intuitive functions that will Get/Set/Remove the object. The beauty of it is that - there is Intellisense to help us out!

Solution

The solution is quite simple.

  1. Create the Notification object
  2. Create a helper function that will do the dirty work (get;set;remove)

Since we moved TempData outside the controller, we are obliged to send the controller to be able to use the TempData. We send the controller by the keyword this.

PromptNotification.cs

C#
public class PromptNotification //Notification Object
{
    public bool NotificationSuccess { get; set; }
    public string NotificationMessage { get; set; }
}

Helper.cs

C#
public static void SetPromptNotification(Controller controller, bool success,string message)
{
    PromptNotification promptNotification = new PromptNotification
    {
        NotificationSuccess = success,
        NotificationMessage = message
    };
    controller.TempData["PromptNotification"] = promptNotification;
}

public static PromptNotification GetPromptNotification(Controller controller)
{
    try
    {
        PromptNotification promptNotification = controller.TempData["PromptNotification"] 
            as PromptNotification;
        return promptNotification;
     }
     catch (Exception ex)
     {
         // log error here

         return null;
     }
}

public static void RemovePromptNotification(Controller controller)
{
    controller.TempData.Remove("PromptNotification");
}

UserController.cs //set

C#
// add promp message => redirect to index
Helper.SetPromptNotification(this, true, 
    "You will shortly receive an email, please verify your registration.");

MainController.cs //get

C#
// get promptnotification => if it exist => pass it to the view => clear the notification
PromptNotification promptNotification = Helper.GetPromptNotification(this);

if (promptNotification != null)
{
    ViewBag.NotificationSuccess = promptNotification.NotificationSuccess;
    ViewBag.NotificationMessage = promptNotification.NotificationMessage;

    Helper.RemovePromptNotification(this);
}

Index.cshtml

C#
@if (ViewBag.NotificationSuccess != null)
{
    PromptNotification promptNotification = new PromptNotification
    {
        NotificationSuccess = (bool)ViewBag.NotificationSuccess,
        NotificationMessage = ViewBag.NotificationMessage as string
    };
    
    string notificationClassName = String.Empty;

    if (promptNotification.NotificationSuccess == true)
    {
        notificationClassName = "notificationSuccessWrapper";
    }
    else
    {
        notificationClassName = "notificationErrorWrapper";
    }
    
    <div class="@Html.Raw(notificationClassName)">
        @promptNotification.NotificationMessage
    </div>
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Lebanon Lebanon
Passionate Software Developer with over 3 years of experience in the field. In love with the girl next door and the MVC architecture.

Comments and Discussions

 
Questionno Pin
asobreiro8-Aug-14 4:33
asobreiro8-Aug-14 4:33 
once you have an extension from controller class, it´s not outside the controller.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.