2

我是新手,MVC.我已经保存了图像和一些数据,但无法显示保存的图像。我想在主页中显示所有保存的图像。

模型:从模型中获取数据库列表

public List<Products> GenreList()
        {
}

控制器

public ActionResult MYsample()
{
    var MyList = storeDB.GenreList();
    var a= MyList.Count;

    if (a != null)
    {
        foreach (var li in MyList)
        {
            return File(li.fileContent, li.mimeType,li.fileName);
        }
    }
    return View(MyList);
}

看法

    @foreach (var item in Model)
    {
            <img src="@Url.Action("MYsample", "HomeController", new { id = item.ProductID })" alt="@item.Productname" />
    }  
4

1 回答 1

8

您可以首先编写一个控制器操作,将图像提供给响应流:

public ActionResult Image(int id)
{
    // you should add a method to your repository that returns the image 
    // record from the id
    Products image = storeDB.Get(id);
    return File(image.fileContent, image.mimeType);
}

然后在您的主控制器操作中将图像列表发送到视图:

public ActionResult MySample()
{
    var model = storeDB.GenreList();
    return View(model);
}

然后在您的强类型视图中循环遍历图像并通过将其属性指向新创建的控制器操作来<img>为每个图像生成一个标签:src

@model MyList
@foreach (var li in MyList)
{
    <img src="@Url.Action("Image", new { id = li.Id })" alt="" />
}

如果您不想有一个单独的控制器操作来查询数据库并从 id 检索图像记录,您可以使用data URI scheme. 请记住,并非所有浏览器都支持此功能。

所以想法是您的控制器操作会将图像数据发送到视图:

public ActionResult MySample()
{
    var model = storeDB.GenreList();
    return View(model);
}

然后在您的强类型视图中,您可以遍历列表并生成正确的<img>标签:

@model MyList
@foreach (var li in MyList)
{
    <img src="src="data:@(li.mimeType);base64,@(Html.Raw(Convert.ToBase64String(li.fileContent)))" alt="" />
}
于 2013-02-05T09:23:33.877 回答