简体   繁体   中英

Display Image in MVC4 View

Refering this link, I created an QR code image using MessagingToolkit.QRCode.dll. How to display the saved image in the same view with the myLayout.
Controller Code

  [HttpPost]
    public ActionResult GenerateExcelQR(string Command, FormCollection collection)
    {
    if (Command == "Excel")
    {
    //  logic to generate Excel
    }
    else if(Command =="QRCode")
     // qr code logic //
        QRCodeEncoder encoder = new QRCodeEncoder();
        Bitmap img = encoder.Encode(qrcode);
        string path = Server.MapPath("/Images/QRCode.jpg"); 
        img.Save(path, ImageFormat.Jpeg);
        return base.File(path,"image/jpeg"); // Displays the QR image without my layout.
     // return View(path,"image/jpeg");      // Returns an error specifying "Images\QRCode.jpg' or its master was not found or no view engine supports the searched locations."
    }

How to display the QRCode image in the Same View with the layout.
Any suggestions.
EDIT ImageModel.cs

public static class ImageModel
    {
        public static string Image(this HtmlHelper htmlHelper, string path, string alt)
        {
            var img = new TagBuilder("img");
            img.MergeAttribute("src", path);
            img.MergeAttribute("alt", alt);
            return img.ToString(TagRenderMode.SelfClosing);
        }
    }

In view

@model IEnumerable<SampleECommerce.Models.CheckoutModel> // reference to 1st model to return values
@using SampleECommerce.Models; // for Imagemodel

You should return not a file, but a view, and in view render your image. Here Image - is a html helper:

public static HtmlString Image(this HtmlHelper helper, string path, string alt)
{
    var img = new TagBuilder("img");
    img.MergeAttribute("src", path);
    img.MergeAttribute("alt", alt);
    return new HtmlString(img.ToString(TagRenderMode.SelfClosing));
}

And then just use it in a view:

@Html.Image(path_to_your_image, "Description")

And in your controller use just return View();

To use this helper, you should create a folder in your project, for example 'Helpers'. Then, create file in this folder, for example 'HtmlImageHelper.cs', then put the content of helper in this file. After this, in your view at the top write: using YourProjectName.Helpers . After this you are able to use this html helper to render images

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM