Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass image from controller and display in a view using ViewBag in ASP.NET MVC 3

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.

like image 702
Leron_says_get_back_Monica Avatar asked Apr 22 '13 08:04

Leron_says_get_back_Monica


People also ask

How pass data from controller view using ViewBag in MVC?

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.

How do you pass data from controller to view and from view to controller?

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.

Can we pass data from view to controller using ViewBag?

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.

How display ViewBag value in MVC?

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.


2 Answers

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.

like image 191
von v. Avatar answered Sep 20 '22 17:09

von v.


Try this:

ViewBag.Logo = Url.Content("~/Content/Images/Logo.png");
like image 24
karaxuna Avatar answered Sep 21 '22 17:09

karaxuna