I guess it's something very straight forward but I can't find out how to do it. In my controller I have:
public ViewResult ShowForm()
{
ViewBag.Title = Resources.ApplicationTitle;
ViewBag.LabelStatus = Resources.Status;
//Logo
ViewBag.Logo =@"C:\Images\Logo.png";
return View("ShowForm");
}
And in my view I try this:
<div id="drawForm">
<img src="@ViewBag.Logo" alt="Logo" />
</div>
However when I run this I just get the "Logo" text.
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.
This can be accessed in the view like @ViewBag.Name. You can assign a primitive or a complex type object as a value to ViewBag property. You can assign any number of properties and values to ViewBag.
Use Server.MapPath
to get the correct path of the image. Suppose your images folder is inside the Content
folder that is normally included in an MVC project. You can do something like this:
public ViewResult ShowForm()
{
//Logo
ViewBag.Logo = Server.MapPath("~") + @"Content\Images\Logo.png";
return View("ShowForm");
}
And you don't have to change the code in your view.
Try this:
ViewBag.Logo = Url.Content("~/Content/Images/Logo.png");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With