In this post we will see how we can upload file in ASP.NET MVC and save the form data into MS SQL Database. The example will contain a form with product information and its image. Users have to enter product information and select the image. The image will be saved in a folder and its path will be saved into database.
Please make sure you create a folder with name “UploadedFile” in your project to follow this tutorial. Okay. Let’s start.
ASP.NET MVC File Upload Example
We will first quickly show How to upload file in ASP.NET MVC.
Create a model class in your project’s Model folder with name Products.cs and edit it as below:
Model>Products.cs:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; namespace MVCSample.Models { public class Products { [DisplayName("Product Name")] public string ProductName { get; set; } [DisplayName("Product Desc")] public string ProductDesc { get; set; } [DisplayName("Product Image")] public string ProductImg { get; set; } public HttpPostedFileBase UploadFile { get; set; } } }
Create a MVC controller with name Products:
Controllers>ProductsController.cs:
using MVCSample.Models; using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; namespace MVCSample.Controllers { public class ProductsController : Controller { // GET: Products public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Products obj) { try { string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss"); string finalPath = "\\UploadedFile\\" +strDateTime +obj.UploadFile.FileName; obj.UploadFile.SaveAs(Server.MapPath("~")+finalPath); obj.ProductImg = finalPath; ViewBag.Message = "Saved Successfully"; return View(); }catch(Exception ex) { ViewBag.Message = ex.Message.ToString(); return View(); } } } }
Now add a View for this Controller inside the Views folder as below:
Views>Products>Index.cshtml:
@model MVCSample.Models.Products @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <link href="~/Content/bootstrap.css" rel="stylesheet" /> <title>Index</title> </head> <body style="padding:5px;"> @using (Html.BeginForm("Index", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <h1> MVC File Upload Example </h1> <hr /> <div> <table class="table-condensed"> <tr> <td> @Html.LabelFor(m => m.ProductName) </td> <td> @Html.TextBoxFor(m => m.ProductName) </td> </tr> <tr> <td> @Html.LabelFor(m => m.ProductDesc) </td> <td> @Html.TextBoxFor(m => m.ProductDesc) </td> </tr> <tr> <td> @Html.LabelFor(m => m.ProductImg) </td> <td> <input type="file" name="UploadFile" required /> </td> </tr> <tr> <td> <input type="submit" name="submit" value="Submit" /> </td> </tr> <tr> <td colspan="3"> @ViewBag.Message </td> </tr> </table> </div> } <div> </div> </body> </html>
Explanation:
Here, we are passing the Product model class object from our View to the [HttpPost] method of our controller’s Index method.
Important thing is to use:
<input type="file" name="UploadFile" required />
name of the input control same as our Model’s class HttpPostedFileBase variable.
public HttpPostedFileBase UploadFile { get; set; }
When the Model Obj with filepath hits our Controller method, it will get saved:
[HttpPost] public ActionResult Index(Products obj) { try { string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss"); string finalPath = "\\UploadedFile\\" +strDateTime +obj.UploadFile.FileName; obj.UploadFile.SaveAs(Server.MapPath("~")+finalPath); //Using this code
Below is my database script:
Create database MVCSample use MVCSample create table tblProducts ( ProductId int not null identity(1,1) primary key, ProductName nvarchar(50) null, ProductDesc nvarchar(50) null, ProductImage nvarchar(100) null, OnDate datetime default getDate() ) create procedure AddProducts ( @Name nvarchar(50), @Desc nvarchar(50), @Image nvarchar(100) ) as begin insert into tblProducts (ProductName, ProductDesc, ProductImage) values (@Name,@Desc,@Image) end --Select * from tblProducts
Now edit the Controller to save the file as well as the data in our database:
Controllers>ProductsController.cs:
using MVCSample.Models; using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; namespace MVCSample.Controllers { public class ProductsController : Controller { SqlConnection con; SqlDataAdapter adapter; SqlCommand cmd; static String connectionString = @"Data Source=192.168.100.39;Initial Catalog=MVCSample;User ID=sa;Password=789;Integrated Security=True;"; // GET: Products public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Products obj) { try { string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss"); string finalPath = "\\UploadedFile\\" +strDateTime +obj.UploadFile.FileName; obj.UploadFile.SaveAs(Server.MapPath("~")+finalPath); obj.ProductImg = finalPath; ViewBag.Message = SaveToDB(obj); return View(); }catch(Exception ex) { ViewBag.Message = ex.Message.ToString(); return View(); } } public string SaveToDB(Products obj) { try { con = new SqlConnection(connectionString); cmd = new SqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "AddProducts"; cmd.Parameters.AddWithValue("@Name", obj.ProductName); cmd.Parameters.AddWithValue("@Desc", obj.ProductDesc); cmd.Parameters.AddWithValue("@Image", obj.ProductImg); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Dispose(); con.Close(); return "Saved Successfully"; }catch(Exception ex) { return ex.Message.ToString(); } } } }
If you liked this post and found it useful, please like our Facebook page and share this with your friends and other people. Thank You so much for your time. Hope you found this post useful.
See Also:
ASP.NET MVC Add and Retrieve Cookies Example.
MVC Login Page using SQL Database and Razor
Binding Angular JS Bind HTML table from SQL in ASP.NET MVC C#
Bind|Populate ASP.NET MVC C# Dropdownlist from SQL
C# ASP.NET MVC Add and Retrieve Cookies
Creating a Login Page in ASP.NET MVC C# using SQL table and Razor
Creating a Registration page in ASP.NET C#