![](/img/trans.png)
[英]In Jquery Img Tag in not populating image from DB because Src appending View path location in source that i cant remove ?? MVC
[英]Trying to call and bind image in img src tag from server in mvc
嗨,我正在尝试在 mvc 中的 img 标签中绑定图像。这个标签在 asp.net 中像这样使用,就像我想在 MVC/例如 ASP.net 中绑定图像一样
<img alt="User Image" width="80px" height="80px" class="img img-thumbnail" src='<%="http://196.0.2.201/p001.ashx?pf=YY&cid="+Session[CommonConstants.SESSION_USER_ID] %>'/>
在 mvc
我想通过@ViewBag.session
作为参数而不是Session[CommonConstants.SESSION_USER_ID]
如何在 Mvc 中实现它任何想法将不胜感激。
如果您使用的是 MVC,为什么不在构建页面时在服务器上使用 base64 图像并将其嵌入图像 src 中,例如使用 Razor:
<img src="data:image/jpeg;base64, @Model.Base64Image">
这样,用于生成图像的任何逻辑都是构建页面的同一控制器逻辑的一部分。 循序渐进:您的剃须刀页面将在顶部有一个@model ViewModel 指令,在您要填充的某处有一个图像元素,jpeg 部分可以是任何图像类型,必须与正在编码的类型相匹配。 在这种情况下,您的视图模型应该有一个名为 Base64Image 的字符串属性。 你的控制器应该有一个部分来获取和转换图像,例如
public IActionResult Index()
{
var model = new ViewModel();
// important thing here is to convert the image into a byte array:
var imageBytes = System.IO.File.ReadAllBytes(@"image.jpeg");
// Convert byte array to Base64 String
model.Base64Image = Convert.ToBase64String(imageBytes);
// return View model with base64 encoded image to page
return View(model);
}
客户端呈现的页面将具有类似这样的图像元素。
<img src="data:image/jpeg;base64, TWFuIGlzIGRpc3RpbmdR== ">
base64 编码将有数百个字符长。 这样做客户端不需要进行第二次调用来获取已经在页面中的图像。 您要做的是定义客户端将调用以获取图像的端点。
声明一个新模型
public class ModelImg { public int MyProperty1 { get; set; } public bool MyProperty2 { get; set; } public string Img { get; set; } }
在控制器中使用您的对象:
ModelImg model = new ModelImg(){Img = @"MyImgAsString",MyProperty1 = 1,MyProperty2 = true};
将您的对象或 img 直接分配给控制器视图中的 ViewData:
ViewData["Img"] = model.Img;
在您的视图中分配您的 src :
<img alt="User Image" width="80px" height="80px" class="img img-thumbnail" src='ViewData["Img"]'/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.