Passing an object array as TempData[] to view

user1752532 picture user1752532 · Apr 8, 2015 · Viewed 9.8k times · Source

I would like to return two values from a post action to the view in a RedirectToAction . TempData[] seems like the ideal option , as the data is only used to show a success message once the user has saved.

I would like to show a small thumbnail of the image that the user just saved and the title of the saved item, in the success message.

Currently I am passing all the data as a new MvcHtmlString

TempData["SaveMsg"] = new MvcHtmlString("<img src=" + model.ImageUrl + " //> <h3//>" + model.Name + " has been saved.<//h3//> " ) ;

I would like to send it as an object[]

TempData["SaveMsg"] = new object[]{model.ImageUrl , model.Name}

Then I would be able to pass the objects into an HtmlHelper and write the conditions for the message display.

I just do not know how to access the object in the view

@TempData["SaveMsg"][0] // (O.o) // Error Cannot apply indexing with 
                                 //  [] to an expression of type 'object'

Is this even possible?

Answer

hutchonoid picture hutchonoid · Apr 8, 2015

You access them in a view by casting them to an object array first then indexing them i.e.

@{
  var objectArray = (object[]) TempData["SaveMsg"];
}

@objectArray[0]
@objectArray[1]

.Net fiddle