Use these instructions to upload an image to a database and display it in an ASP.NET MVC GridView. This example will show how to accept picture uploads, store them in a SQL Server database, and retrieve them for display.
Step 1: Set Up Your Database
- Create a SQL Server Database:Open SQL Server Management Studio (SSMS).
- Create a new database named ImageUploadDB.
- Create a Table for Images:Execute the following SQL script to create a table that will store image details:
sql
- CREATE TABLE Images (
- Id INT PRIMARY KEY IDENTITY(1,1),
- Name NVARCHAR(100),
- ContentType NVARCHAR(50),
- Data VARBINARY(MAX)
- );
Step 2: Create the ASP.NET MVC Project
- Open Visual Studio.
- Create a new ASP.NET MVC project:Go to File > New > Project.
- Select ASP.NET Web Application and name your project (e.g., ImageUploadApp).
- Choose the MVC template and click OK.
Step 3: Create the Model
- Create a Model Class:In the Models folder, create a new class named ImageModel.cs:
csharp
- public class ImageModel
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string ContentType { get; set; }
- public byte[] Data { get; set; }
- }
Step 4: Create the Controller
- Create a Controller:Right-click on the Controllers folder and add a new controller named ImageController.cs:
csharp
- using System;
- using System.Collections.Generic;
- using System.Data.SqlClient;
- using System.IO;
- using System.Web;
- using System.Web.Mvc;
- using YourNamespace.Models; // Update with your actual namespace
- public class ImageController : Controller
- {
- private string connectionString = “YourConnectionStringHere”; // Update with your connection string
- public ActionResult Index()
- {
- List<ImageModel> images = new List<ImageModel>();
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand(“SELECT * FROM Images”, conn);
- SqlDataReader reader = cmd.ExecuteReader();
- while (reader.Read())
- {
- images.Add(new ImageModel
- {
- Id = (int)reader[“Id”],
- Name = reader[“Name”].ToString(),
- ContentType = reader[“ContentType”].ToString(),
- Data = (byte[])reader[“Data”]
- });
- }
- }
- return View(images);
- }
- [HttpPost]
- public ActionResult Upload(HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0)
- {
- byte[] data;
- using (var binaryReader = new BinaryReader(file.InputStream))
- {
- data = binaryReader.ReadBytes(file.ContentLength);
- }
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand(“INSERT INTO Images (Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)”, conn);
- cmd.Parameters.AddWithValue(“@Name”, Path.GetFileName(file.FileName));
- cmd.Parameters.AddWithValue(“@ContentType”, file.ContentType);
- cmd.Parameters.AddWithValue(“@Data”, data);
- cmd.ExecuteNonQuery();
- }
- }
- return RedirectToAction(“Index”);
- }
- }
Step 5: Create the Index View
- Create the Index View:Right-click on the Index action in ImageController and select Add View.
- Name the view Index.cshtml.
xml
- @model IEnumerable<YourNamespace.Models.ImageModel> // Update with your actual namespace
- @{
- ViewBag.Title = “Image Upload”;
- }
- <h2>Upload Image</h2>
- @using (Html.BeginForm(“Upload”, “Image”, FormMethod.Post, new { enctype = “multipart/form-data” }))
- {
- <div>
- <input type=”file” name=”file” />
- <input type=”submit” value=”Upload” />
- </div>
- }
- <h2>Uploaded Images</h2>
- <table class=”table”>
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Image</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var image in Model)
- {
- <tr>
- <td>@image.Id</td>
- <td>@image.Name</td>
- <td>
- <img src=”@Url.Action(“GetImage”, “Image”, new { id = image.Id })” alt=”@image.Name” style=”width:100px;height:100px;” />
- </td>
- </tr>
- }
- </tbody>
- </table>
Step 6: Create the GetImage Action
- Add a method to retrieve the image in ImageController:csharp
- public ActionResult GetImage(int id)
- {
- ImageModel image = null;
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand(“SELECT * FROM Images WHERE Id = @Id”, conn);
- cmd.Parameters.AddWithValue(“@Id”, id);
- SqlDataReader reader = cmd.ExecuteReader();
- if (reader.Read())
- {
- image = new ImageModel
- {
- Id = (int)reader[“Id”],
- Name = reader[“Name”].ToString(),
- ContentType = reader[“ContentType”].ToString(),
- Data = (byte[])reader[“Data”]
- };
- }
- }
- if (image != null)
- {
- return File(image.Data, image.ContentType);
- }
- return HttpNotFound();
- }
Step 7: Configure the Connection String
- Update Connection String:Open Web.config and add your connection string inside the <connectionStrings> section:
xml
- <connectionStrings>
- <add name=”DefaultConnection” connectionString=”Data Source=YOUR_SERVER;Initial Catalog=ImageUploadDB;Integrated Security=True” providerName=”System.Data.SqlClient” />
- </connectionStrings>
- Update the connectionString variable in the ImageController to use this connection string:
csharp
private string connectionString = ConfigurationManager.ConnectionStrings[“DefaultConnection”].ConnectionString;
Step 8: Run Your Application
- Start the Application:Press F5 to run your application.
- Navigate to /Image/Index to access the upload page.
- Upload an image and see it displayed in the GridView.
Conclusion
Using ASP.NET MVC, you may upload photographs to a SQL Server database and show them in a GridView. The photos are saved as binary data in the database and retrieved for display via an action method that returns the image data as a file. You can improve this implementation by including features like validation, error handling, and user authentication.