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>
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)"
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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.