2

I'm new to MVC 3 and still learning. I'm currently building a static 2 page website which has a different image on both pages but are located in the same place. I have been told that I can use the ViewBag to change this image depending on what page I am on, however I have not got a clue where to begin with applying this to my website.

Any help will be greatly appreciated. Thank You for your time.

user1957778
  • 247
  • 3
  • 5
  • 10

4 Answers4

3

On your controller's Action method,make ViewBag or ViewData like this

ViewBag.Imagename="nameofimage";

ViewData["img"]="nameofimage";

On your view, you can make img tag like this

<img src="@ViewBag.Imagename">

or if you have created ViewData

<img src="@ViewData["img"]">
Syed Salman Raza Zaidi
  • 2,172
  • 9
  • 42
  • 87
2

For some reason, it did not work for me when I simply tried using

@ViewBag.BackgroundImage = "~/Content/images/image.jpg"
...
<img src="@ViewBag.BackgroundImage" />

But what did work for me was

@ViewBag.BackgroundImage = "image.jpg"
...
<img src = "~/Content/images/@(ViewBag.BackgroundImage)" />
hallordylo
  • 53
  • 2
  • 9
0

personally i dont like specifying anything view related in controller, i am using naming convention between action method names and images:

<img src="~/Content/images/@(ViewContext.RouteData.Values["action"].ToString().ToLower())_img.jpg">

and picture name for index action method would be "index_img.jpg"

sanjuro
  • 1,611
  • 1
  • 21
  • 29
0

For those who want use full path in viewbag, use this

@ViewBag.BackgroundImage = "Content/images/image.jpg"
...
<img src="~/@ViewBag.BackgroundImage" />

The reason why hallordylo example not working with full path is missing "~/" in src="..." and this sign "~/" should not be inside ViewBag.

Wanderer
  • 319
  • 1
  • 3
  • 12