0

I want to upload and display an image to the database. I have a model to add EmployeeFirstName, LastName,... and employee image. When I post form all data posted except the image file.

Here is my code.

Model:

namespace EmployeeTask.Models
{
   using System;
   using System.Collections.Generic;

   public partial class Employee
   {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Department { get; set; }
        public Nullable<System.DateTime> HiringDate { get; set; }
        public byte[] Image { get; set; }
   }
}

View:

<div id="dialogEmployeeEditor">
<div>
    <h2>Add/Edit Employee</h2>
    <table>
        <tr>
            <td><a href="javascript:EmployeeEditor_Save();">Save</a></td>
        </tr>
    </table>
</div>

<div id="Container">
    <form id="frmEmployeeEditor">
        <table border="1">
            <tr>
                <td>First Name</td>
                <td>
                    <input type="text" name="FirstName" id="EmployeeEditor_FirstName" value="@emp.FirstName" />
                </td>
            </tr>
           .........

            <tr>
                <td>Upload Image</td>
                <td>
                    <input type="file" name="imageFile" id="image" />
                </td>
            </tr>
        </table>
        <input type="hidden" name="employeeId" value="@emp.Id" />
    </form>
</div>
</div>

<script type="text/javascript">
function EmployeeEditor_Save() {
    $.post("/Employees/SaveEmployee", $("#frmEmployeeEditor").serialize(), function (e) {

        $("#EmployeesGridContainer").replaceWith($(e));
        $("#PopUpContaine").dialog("close");
    }, "json");
}
</script>

Controller:

[HttpPost]
public ActionResult SaveEmployee(int employeeId)
{

        SaveEmployeeDate(employeeId,Request.Form);
        return PartialView("_EmployeesGrid");
}

public void SaveEmployeeDate(int employeeId, NameValueCollection Data)
{
        Employee emp = db.Employees.FirstOrDefault(c => c.Id == employeeId);

        if (emp == null)
        {
            emp = db.Employees.Create();
            db.Employees.Add(emp);
        }

        emp.FirstName = Data["FirstName"];
        emp.MiddleName = Data["MiddleName"];
        emp.LastName = Data["LastName"];
        emp.HiringDate = Convert.ToDateTime(Data["HiringDate"]);
        emp.Department = Data["Department"];

        HttpPostedFileBase image = Request.Files["imageFile"];

        if (image != null && image.ContentLength > 0)
        {
            byte[] imageBytes = new byte[image.ContentLength];
            image.InputStream.Read(imageBytes, 0, image.ContentLength);
            emp.Image = imageBytes;
        }

        db.SaveChanges();
}
1

1 Answer 1

5

In order to get HttpPostedFileBase types to post correctly, you need to add enctype="multipart/form-data" to your form header. You could just write it manually as <form id="frmEmployeeEditor" enctype="multipart/form-data">, but I would recommend using MVC's form helpers to do the same thing like this (in your cshtml view):

@using (Http.BeginForm("Employee", "SaveEmployee", FormMethod.Post, new {enctype="multipart/form-data"}) 
{
     // Your form goes here
    <input type="file" name="imageFile" id="image" />
}

Then, in your controller, you can simply add a parameter to your post action that will get the file automatically, like this:

public ActionResult SaveEmployee(int employeeId, HttpPostedFileBase imageFile)
{
    // Controller code here
}

imageFile should no longer be null and you can save it to disk, or get the bytes to save to the database.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.