如何在视图中渲染(图像)模型中的数据?

时间:2014-10-31 20:44:29

标签: asp.net-mvc-4 razor

那是我的控制器动作

public ActionResult ViewImage(int? productId){

           var image = (from x in db.Images
                             where (x.ProductId == productId)
                             select x).ToList();
            return View(image);
       }

这就是我的观点

@model
@{
    ViewBag.Title = "ViewImage";
}

<h2>Uploaded pictures</h2>
<div>
<br>
        <img height="300" width="350 " src="@Model" />
</div>
<div>
    <br>
    @Html.ActionLink("Back to Index","Index","Products")
</div>

我不知道在@model之后我要放什么。我试图把图像类型但不起作用!

4 个答案:

答案 0 :(得分:0)

您需要发送模型类型

@model List<Images>

答案 1 :(得分:0)

Add following property to the model class and add images to it.


public IEnumerable<HttpPostedFileBase> AttachImages { get; set; }

答案 2 :(得分:0)

尝试使用ViewBag.Image而不是var image:

public ActionResult ViewImage(int? productId){
           Viewbag.Image image = (from x in db.Images
                       where (x.ProductId == productId)
                       select x).ToList();
            return View(image);
}

现在在你看来:

@{
    ViewBag.Title = "ViewImage";
}

<h2>Uploaded pictures</h2>
<div>
<br>

@foreach(var image in Viewbag.Image)
{
        <img height="300" width="350 " src="@image" />
}
</div>
<div>
    <br>
    @Html.ActionLink("Back to Index","Index","Products")
</div>

希望这有帮助

答案 3 :(得分:0)

您应该有一个控制器操作,将图像流式传输到响应:

public ActionResult Image(int imageId)
{
    var image = db.Images.SingleOrDefault(x => x.Id == imageId);
    if (image == null)
    {
        return HttpNotFound();
    }

    byte[] imageData = image.Data; // or whatever byte[] property you have
    string contentType = "image/jpg"; // or if you have stored the content type in your DB simply assign it to image.ContentType
    return File(imageData, contentType);
}

好的,有了这个方便的方法,您可以更新您的视图:

@model IList<WebApplication1.Image>

<h2>Uploaded pictures</h2>
<div>
    @foreach(var image in Model)
    {
        <img height="300" width="350 " src="@Url.Action("Image", "SomeController", new { imageId = image.Id })" />
    }
</div>

注意图像的src属性是如何指向我们之前实现的控制器操作,它将获取图像并将其传输到响应。