2

I am trying to pass an image stored in a viewmodel from my controller to my razor view. The two [barcode] images (System.Drawing.Image) are defined as below:

ShippingSummaryViewModel shippingSummaryVm = ShippingSummaryViewModel.ToShippingSummaryFromOrder(orders);
shippingSummaryVm.CustIdBarcode = CreateBarcode(shippingSummaryVm.customer_code);
shippingSummaryVm.SalesOrderBarcode = CreateBarcode(shippingSummaryVm.order_id);

in my view, I would like to be able to use an <img> tag to reference these images but I am not sure what to put for the source as setting the src equal to @Model.CustIdBarcode does not work due to getting a 404 resource not found error. All help is appreciated

Edit: In my razor view, I am using <img src="@Model.SalesOrderBarcode"/> and <img src="@Model.CustIdBarcode" /> to try and display the images. These fields in my viewmodel look like:

public Image SalesOrderBarcode { get; set; }
public Image CustIdBarcode { get; set; }

and the errors I get when rendering the page are:

GET http://localhost:63957/Orders/System.Drawing.Bitmap 404 (Not Found)
GregH
  • 5,125
  • 8
  • 55
  • 109

3 Answers3

5

HTML images are generally linked to another request on the server, so passing the System.Drawing.Image is not the best way to do this. Modern browsers can have inline images (base64 encoded), but the best bet is to create a different action on the controller that you can link to:

public class MyController {
  public ActionResult GetCustIdBarCode(Guid code) {
    var img = CreateBarcode(code);

    // I'm not sure if the using here will work or not. It might work
    // to just remove the using block if you have issues.
    using (var strm = new MemoryStream()) {
      img.Save(strm, "image/png");
      return File(strm, "image/png");
    }
  }

  public ActionResult GetSalesBarcode(Guid salesId) {
    // Similar to above method
  }
}

And then in your view, you'd have something like:

<img src="@Url.Action("GetCustIdBarCode", new { code = customer_code })" />

https://stackoverflow.com/a/11546957/179311

Community
  • 1
  • 1
bradlis7
  • 3,375
  • 3
  • 26
  • 34
1

In your View try like this

<img src= "@Url.Content(Model.ImagePath)" alt="Image" />
Linh Tuan
  • 440
  • 3
  • 11
  • I don't have a path to my image as I don't want to store it anywhere (it will have a very short lifespan). My viewmodel directly contains the image I'd like to render – GregH May 02 '16 at 16:33
  • So that you can return image to base64 in action result – Linh Tuan May 02 '16 at 16:38
0

Try the following syntax:

<img src="@Url.ImagePath(Model.CustIdBarcode)" />
taquion
  • 2,667
  • 2
  • 18
  • 29