Search code examples
asp.net-mvcviewbag

MVC Shared Routine that uses viewbag


I have a helper routine that I use in multiple views that wraps up some nifty bootstrap formatting to display a message.

@MyHelpers.StatusMessage(ViewBag.Status, ViewBag.StatusMessage)

In order for this to work I have to use tempdata briefly (in case of redirect) and then put the values back in the viewbag.

Like so:

@{
    // View Init 

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    // In case we are here due to a redirect... 
    if (!String.IsNullOrEmpty((string)TempData["Status"]))
    {
        ViewBag.Status = TempData["Status"];

    }
    if (!String.IsNullOrEmpty((string)TempData["StatusMessage"]))
    {
        ViewBag.StatusMessage = TempData["StatusMessage"];
    } 

}

I would really like this to be a common routine like my helper, but I can't access the viewbag from there.

Is there somewhere I can place the shared code and still access the viewbag?

I'm open to alternative ways of doing this as well... I realize that I might be doing this the hard way...

Thanks.

Resolution:

Not perfect, but does allow for reuse and saves a few lines of code.

@helper SetStatusInfoFromTempData(dynamic viewBag, string status, string statusMessage)    
{

        // In case we are here due to a redirect... 
    if (!String.IsNullOrEmpty(status))
    {
        viewBag.Status = status;

    }
    if (!String.IsNullOrEmpty(statusMessage))
    {
        viewBag.StatusMessage = statusMessage;
    }

}

Solution

  • The ViewBag is a dynamic, so you can add it to your helper method as a parameter for shared processing:

    public void MyHelperMethod(dynamic viewBag, Dictionary<string, string> tempData)
    {
        // In case we are here due to a redirect... 
        if (!String.IsNullOrEmpty((string)tempData["Status"]))
        {
            viewBag.Status = tempData["Status"];
        }
    
        if (!String.IsNullOrEmpty((string)tempData["StatusMessage"]))
        {
            viewBag.StatusMessage = tempData["StatusMessage"];
        }         
    }
    

    P.S. I guessed your data type for TempData to be a dictionary, please correct as needed.