Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 从数据库读取图像并在视图中显示_Asp.net Mvc_C# 4.0_Gridview_Partial Views - Fatal编程技术网

Asp.net mvc 从数据库读取图像并在视图中显示

Asp.net mvc 从数据库读取图像并在视图中显示,asp.net-mvc,c#-4.0,gridview,partial-views,Asp.net Mvc,C# 4.0,Gridview,Partial Views,我正在尝试将旧的ASP.NET应用程序转换为MVC,我只是在学习MVC。我需要在Gridview中显示图像。映像本身作为数据类型映像存储在SQL Server表中。下面是以前使用的代码。有人能推荐一种使用MVC的方法吗?我正在考虑创建一个可以嵌入到标准视图中的部分页面,但不确定这是否是要实现的正确设计 感谢是前进 ` string sqlText = "SELECT * FROM Images WHERE img_pk = " + id; SqlConnection co

我正在尝试将旧的ASP.NET应用程序转换为MVC,我只是在学习MVC。我需要在Gridview中显示图像。映像本身作为数据类型映像存储在SQL Server表中。下面是以前使用的代码。有人能推荐一种使用MVC的方法吗?我正在考虑创建一个可以嵌入到标准视图中的部分页面,但不确定这是否是要实现的正确设计

感谢是前进

   `  string sqlText = "SELECT * FROM Images WHERE img_pk = " + id;
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);

        SqlCommand command = new SqlCommand(sqlText, connection);
        connection.Open();
        SqlDataReader dr = command.ExecuteReader();
        if (dr.Read())
        {
            //Response.Write("test");
           Response.BinaryWrite((byte[])dr["img_data"]);
        }
        connection.Close();
    }
然后可以使用此图像标记引用它:

<asp:Image Height="73" Width="80" ID="Image1" ImageAlign="Middle" ImageUrl='<%#"viewimage.aspx?id=" + Eval("ImageId") %>' runat="server"/></a></td>

第一件事是忘记ASP.NET MVC应用程序中的GridView。服务器端控件、回发、视图状态、事件等。。。所有这些都是不再存在的概念

在ASP.NET MVC中,您可以使用模型、控制器和视图

因此,您可以编写一个控制器操作,从数据库中获取图像并为其提供服务:

public class ImagesController: Controller
{
    public ActionResult Index(int id)
    {
        string sqlText = "SELECT img_data FROM Images WHERE img_pk = @id";
        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
        using (var command = conn.CreateCommand())
        {
            conn.Open();
            command.CommandText = sqlText;
            command.Parameters.AddWithValue("@id", id);
            using (var reader = command.ExecuteReader())
            {
                if (!reader.Read())
                {
                    return HttpNotFound();
                }

                var data = GetBytes(reader, reader.GetOrdinal("img_data"));
                return File(data, "image/jpg");
            }
        }
    }

    private byte[] GetBytes(IDataReader reader, int columnIndex)
    {
        const int CHUNK_SIZE = 2 * 1024;
        byte[] buffer = new byte[CHUNK_SIZE];
        long bytesRead;
        long fieldOffset = 0;
        using (var stream = new MemoryStream())
        {
            while ((bytesRead = reader.GetBytes(columnIndex, fieldOffset, buffer, 0, buffer.Length)) > 0)
            {
                byte[] actualRead = new byte[bytesRead];
                Buffer.BlockCopy(buffer, 0, actualRead, 0, (int)bytesRead);
                stream.Write(actualRead, 0, actualRead.Length);
                fieldOffset += bytesRead;
            }
            return stream.ToArray();
        }
    }
}
然后在你看来:

<img src="@Url.Action("Index", "Images", new { id = "123" })" alt="" />
然后为您正在使用的数据提供程序实现此方法:

public class ImagesRepositorySql: IImagesRepository
{
    public byte[] GetImageData(int id)
    {
        // you already know what to do here.
        throw new NotImplementedException();
    }
}
最后,您的控制器将变得与数据库无关。应用程序中的层现在在它们之间弱耦合,这将允许您单独重用和单元测试它们:

public class ImagesController: Controller
{
    private readonly IImagesRepository _repository; 
    public ImagesController(IImagesRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index(int id)
    {
        var data = _repository.GetImageData(id);
        return File(data, "image/jpg");
    }
}

最后一部分是配置您最喜欢的DI框架,以便将存储库的正确实现注入控制器。

第一件事是忘记ASP.NET MVC应用程序中的GridView。服务器端控件、回发、视图状态、事件等。。。所有这些都是不再存在的概念

在ASP.NET MVC中,您可以使用模型、控制器和视图

因此,您可以编写一个控制器操作,从数据库中获取图像并为其提供服务:

public class ImagesController: Controller
{
    public ActionResult Index(int id)
    {
        string sqlText = "SELECT img_data FROM Images WHERE img_pk = @id";
        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
        using (var command = conn.CreateCommand())
        {
            conn.Open();
            command.CommandText = sqlText;
            command.Parameters.AddWithValue("@id", id);
            using (var reader = command.ExecuteReader())
            {
                if (!reader.Read())
                {
                    return HttpNotFound();
                }

                var data = GetBytes(reader, reader.GetOrdinal("img_data"));
                return File(data, "image/jpg");
            }
        }
    }

    private byte[] GetBytes(IDataReader reader, int columnIndex)
    {
        const int CHUNK_SIZE = 2 * 1024;
        byte[] buffer = new byte[CHUNK_SIZE];
        long bytesRead;
        long fieldOffset = 0;
        using (var stream = new MemoryStream())
        {
            while ((bytesRead = reader.GetBytes(columnIndex, fieldOffset, buffer, 0, buffer.Length)) > 0)
            {
                byte[] actualRead = new byte[bytesRead];
                Buffer.BlockCopy(buffer, 0, actualRead, 0, (int)bytesRead);
                stream.Write(actualRead, 0, actualRead.Length);
                fieldOffset += bytesRead;
            }
            return stream.ToArray();
        }
    }
}
然后在你看来:

<img src="@Url.Action("Index", "Images", new { id = "123" })" alt="" />
然后为您正在使用的数据提供程序实现此方法:

public class ImagesRepositorySql: IImagesRepository
{
    public byte[] GetImageData(int id)
    {
        // you already know what to do here.
        throw new NotImplementedException();
    }
}
最后,您的控制器将变得与数据库无关。应用程序中的层现在在它们之间弱耦合,这将允许您单独重用和单元测试它们:

public class ImagesController: Controller
{
    private readonly IImagesRepository _repository; 
    public ImagesController(IImagesRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index(int id)
    {
        var data = _repository.GetImageData(id);
        return File(data, "image/jpg");
    }
}

最后一部分是配置您最喜欢的DI框架,以便将存储库的正确实现注入控制器。

代码是操作方法,图像控件是图像标记,图像url是图像标记的操作url。代码是动作方法,图像控件是图像标记,图像url是图像标记的动作url。有点像。+1,用于教授IoC和存储库模式,回答无辜的图像显示问题:谢谢回答Darin!我插入了你的代码,没有做太多修改就成功了。我现在需要更多地了解它,以便更好地理解它。我不喜欢只使用代码示例而不知道它是如何工作的。+1用于教授IoC和存储库模式,回答无辜的图像显示问题:谢谢回答Darin!我插入了你的代码,没有做太多修改就成功了。我现在需要更多地了解它,以便更好地理解它。我不喜欢只使用代码示例而不知道它是如何工作的。