I am going to develop an image upload application step by
step in Asp.Net MVC 4.0. It is sometimes required to upload image in application.
It is sample application and you can upload one image against an employee.
Step 1. Open Visual
Studio and click on the File à
New Project. Select ASP.Net MVC 4.0 Web application as shown below.
Step 2. Give the
project name as ImageUploadProject.
Step 3. Select Internet Application template as shown below
and click on the OK button.
Step 4. Run the
application you will see the below screen in the browser.
Step 6. In the
SQL Server create Database EmployeeDB and table Employee as shown below.
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[Address] [nvarchar](50) NULL,
[ZipCode] [nvarchar](50) NULL,
CONSTRAINT
[PK_Employee] PRIMARY KEY
CLUSTERED
(
[EmployeeID] ASC
)WITH
(PAD_INDEX
= OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Step 7. Browse the solution and locate Model folder. Add Employee class as shown below
public class Employee {
public int EmployeeID { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
[NotMapped]
public HttpPostedFileBase Image { get; set; }
[NotMapped]
[Display(Name = "Image")]
public string ImageFile { get; set; }
}
Step 8. Add
EmployeeDBContext class in the Model folder as shown below
public class
EmployeeDBContext:DbContext
{
public DbSet<Employee>
EmployeeCollection { get; set; }
public EmployeeDBContext()
:
base("EmployeeConnection") {
}
protected override void
OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Employee");
})
.Property(m =>
m.EmployeeID).HasColumnName("EmployeeID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
}
}
Step 9. Add Employee Controller as
shown below
Step 10. : Add the
below methods in the Employee Controller.
public ActionResult Create()
{
return View();
}
//
// POST: /Employee/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee
empModel)
{
try
{
using (EmployeeDBContext edb = new
EmployeeDBContext())
{
edb.EmployeeCollection.Add(empModel);
edb.SaveChanges();
PictureUpload(empModel);
}
return
RedirectToAction("Index");
}
catch(Exception ex)
{
return View();
}
}
Step 11. Right click on the Create method and select Add
View method.
Step 12. Add the below tag to upload image
in case if not auto generated in create.cshtml file.
<div class="editor-field">
@Html.TextBoxFor(model => model.Image, new { type = "file" })
@Html.ValidationMessageFor(model => model.Image)
</div>
Step 12. Add below 2 methods in the EmployeeController
class
private void PictureUpload(Employee emp)
{
if (emp.Image.ContentLength > 0)
{
var filePath = Server.MapPath(@"/Content/Uploads");
string savedFileName = Path.Combine(filePath, emp.EmployeeID.ToString()+".jpg");
emp.Image.SaveAs(savedFileName);
}
}
private void DownloadPetPicture(IList<Employee> empList)
{
foreach (var employee in empList)
{
var name = "/Content/Uploads/"+employee.EmployeeID.ToString() +".jpg";
var picture = @UrlHelper.GenerateContentUrl( name, this.HttpContext);
employee.ImageFile = "<img src='" +
picture + "'></img>";
}
}
Step 13. Update the Index
method as shown below
public ActionResult Index()
{
List<Employee> employeeCollection = null;
using (EmployeeDBContext emd = new EmployeeDBContext())
{
employeeCollection = emd.EmployeeCollection.ToList();
if (employeeCollection != null)
DownloadPetPicture(employeeCollection);
}
return View(employeeCollection);
}
Step 14. Create one Uploads folder under Content folder in the solution.
We can write code to auto generate the folder in case it is not available. But I have not coded that. Add strongly view
with index method as shown in previous steps.
Now build and type Employee/create
you will see the below screen
Enter values and select
image it will take you the index(or List) view as shown below
No comments:
Post a Comment