Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6701367
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T06:55:34+00:00 2026-05-26T06:55:34+00:00

I’m trying to convert an older ASP.NET application to MVC (I am just learning

  • 0

I’m trying to convert an older ASP.NET application to MVC (I am just learning MVC). and I have a need to display an image in a Gridview. The image itself is stored in a SQL Server table as datatype image. The code that was used previously is below. Can someone suggest an approach using MVC? I was thinking of creating a partial page that I could embed in a standard view, but not sure if that is the right design to implement.

Thanks is advance!

   `  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();
    }

Then it can be referenced using this image tag:

<asp:Image Height="73" Width="80" ID="Image1" ImageAlign="Middle" ImageUrl='<%#"viewimage.aspx?id=" + Eval("ImageId") %>' runat="server"/></a></td>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T06:55:35+00:00Added an answer on May 26, 2026 at 6:55 am

    The first thing is to forget about GridView in an ASP.NET MVC application. Server side controls, postbacks, viewstate, events, … all those are notions that no longer exists.

    In ASP.NET MVC you work with Models, Controllers and Views.

    So you could write a controller action which will fetch the image from the database and serve it:

    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();
            }
        }
    }
    

    and then in your view simply:

    <img src="@Url.Action("Index", "Images", new { id = "123" })" alt="" />
    

    Now of course all this controller action is nice and dandy, but you should really abstract all data access into a repository:

    public interface IImagesRepository
    {
        byte[] GetImageData(int id);
    }
    

    then implement this method for the data provider you are using:

    public class ImagesRepositorySql: IImagesRepository
    {
        public byte[] GetImageData(int id)
        {
            // you already know what to do here.
            throw new NotImplementedException();
        }
    }
    

    Finally you will have your controller become database agnostic. Layers in your application are now weakly coupled between them which would allow you to reuse and unit test them in isolation:

    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");
        }
    }
    

    and the last part would be to configure your favorite DI framework to inject the proper implementation of the repository into the controller.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
In my XML file chapters tag has more chapter tag.i need to display chapters
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.