ASP.NET MVC:在视图上显示图像

问题描述 投票:0回答:1

我正在尝试在视图中显示图像。

这里我在 SQL Server Express 中添加图像(

price
定义为
int
picture
varbinary(MAX)
列):

insert into products (price, picture) 
    select 499, BulkColumn 
    from Openrowset(Bulk 'C:\Users\tally\Pictures\harddisk-275-183.jpg', Single_Blob) as img

这里我定义了属性:

public class ProductsModel
{
    public Image ProductImage { get; set; }
    public int ProductPrice { get; set; }
}

我使用此控制器方法从数据库获取数据:

[HttpGet]
public IActionResult Products(ProductsModel objProductsModel)
{
    string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Onlineproducts; Integrated Security=True";

    SqlConnection con = new SqlConnection(conStr);
    con.Open();

    SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select * from products", con));
    DataSet dataSet = new DataSet();
    dataAdapter.Fill(dataSet);

    if (dataSet.Tables[0].Rows.Count == 1)
    {
        Byte[] data = new Byte[0];
        data = (Byte[])(dataSet.Tables[0].Rows[0]["picture"]);
        MemoryStream mem = new MemoryStream(data);
        objProductsModel.ProductImage = Image.FromStream(mem);

        objProductsModel.ProductPrice = Convert.ToInt32(dataSet.Tables[0].Rows[0]["price"]);
        return View(objProductsModel);
    }

    return View(objProductsModel);
}

这里我尝试在视图中同时显示图像和价格:

@model Nettbutikk.Models.ProductsModel

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="~/css/products.css" />
</head>
<body>
    <p><h1>Products</h1></p>
    <hr />

        <div class="responsive">
            <div class="gallery">

                <div>@Html.DisplayFor(ProductsModel => ProductsModel.ProductImage)</div>

                <div class="desc">Kr @Html.DisplayFor(ProductsModel => ProductsModel.ProductPrice)</div>
            </div>
        </div>
    </body>
</html>

Price
按应有的方式显示在网页上,但图像却没有。

也许要显示图像,我应该选择

DisplayFor(...)
以外的其他内容?请帮助我。

c# asp.net-mvc sql-server-express
1个回答
0
投票

问题解决了。我在Controller中添加了一个新的Action方法:

public ActionResult GetImage(int id)
{
    string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Nettbutikk; Integrated Security=True";
    SqlConnection con = new SqlConnection(conStr);
    con.Open();

    SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select * from products", con));
    DataSet dataSet = new DataSet();
    dataAdapter.Fill(dataSet);

    
    Byte[] data = new Byte[0];
    data = (Byte[])(dataSet.Tables[0].Rows[0]["picture"]);
       
    return File(data, "image/jpg");
}

然后在View中调用这个方法:

<img src="@Url.Action("GetImage", new { id = 1 })" alt="Northern Lights" width="600" height="400">
© www.soinside.com 2019 - 2024. All rights reserved.