GregH
GregH

Reputation: 5459

c# MVC display image from viewmodel in a razor view

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)

Upvotes: 2

Views: 7581

Answers (3)

bradlis7
bradlis7

Reputation: 3489

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

Upvotes: 5

Linh Tuan
Linh Tuan

Reputation: 458

In your View try like this

<img src= "@Url.Content(Model.ImagePath)" alt="Image" />

Upvotes: 1

taquion
taquion

Reputation: 2767

Try the following syntax:

<img src="@Url.ImagePath(Model.CustIdBarcode)" />

Upvotes: 0

Related Questions