[英]Display Image in MVC4 View
引用此鏈接,我使用MessagingToolkit.QRCode.dll創建了QR碼圖像。 如何在與myLayout相同的視圖中顯示保存的圖像。
控制器代碼
[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."
}
如何在與布局相同的視圖中顯示QRCode圖像。
有什么建議么。
編輯 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);
}
}
視野中
@model IEnumerable<SampleECommerce.Models.CheckoutModel> // reference to 1st model to return values
@using SampleECommerce.Models; // for Imagemodel
您不應返回文件,而應返回視圖,並在視圖中渲染圖像。 此處的圖片-是html幫助器:
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));
}
然后在視圖中使用它:
@Html.Image(path_to_your_image, "Description")
並在您的控制器中使用,只需return View();
要使用此幫助程序,應在項目中創建一個文件夾,例如“ Helpers”。 然后,在此文件夾中創建文件,例如“ HtmlImageHelper.cs”,然后將幫助程序的內容放入此文件中。 之后,在頂部的視圖中輸入: using YourProjectName.Helpers
。 在此之后,您可以使用此html助手來渲染圖像
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.