0

I am trying to use a variable that I set in my controller to be the src inside of an img tag. I copied the string in directly and it worked so I know my path is correct. However, I am having trouble figuring out how to place the variable I create into the img tag.

Here is my controller:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace dojodachi.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        [HttpGet]
        [Route("")]
        public IActionResult Index()
        {
            ViewData["Tree"] = "~/images/regular_tree.jpeg";
            return View();
        }
    }
}

Here is my cshtml file

<div id = wrapper>
    <p>Fullness:    Happiness:      Meals:     Energy</p>
    <div id = inside>
        <img src="@ViewData['Tree']" alt="Regular Tree"> //How do I place my variable in this img tag?
        <p></p>
    </div>
</div>
1
  • It looks like you are using MVC (Model View Controller)... how come you don't have a model? Commented Dec 27, 2016 at 1:53

2 Answers 2

6

Just use single quotes on the outside and double quotes on the property:

<img src='@ViewData["Tree"]'

If you are using C# 4 you could also use ViewBag instead of ViewData.

On controller:

ViewBag.Tree = "~/images/regular_tree.jpeg";

Then on view:

<img src="@Url.Content(ViewBag.Tree)"

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but now for some reason I am getting a 404 error. When I hard code the string in the image shows up, but when I use a variable I get a 404 error
@Aaron If you set the url on the controller with the server relative ~ then use Url.Content to resolve the URL during view rendering.
0

It's an old question, but having similar issue today, so maybe can help others, solved as follow:

Controller:

ViewData["Tree"] = "images/regular_tree.jpeg";

View:

<img src="~/@ViewBag.Tree">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.