Программа заключается в работе с базой данных работников. Не получается загрузить изображения из представления в бд и из бд в представление для показа
Модель работников:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EmployeeBase.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Byte[] Foto { get; set; }
public DateTime BirthDate { get; set; }
public int? DepartmentId { get; set; }
public Department Department { get; set; }
// If i use this - my code dosen't work
//public HttpPostedFileBase FotoFromView { get; set; }
}
}
Контроллер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.IO;
using EmployeeBase.Models;
namespace EmployeeBase.Controllers
{
public class HomeController : Controller
{
CompanyContext db = new CompanyContext();
public ActionResult Index()
{
var employees = db.Employees.Include(e => e.Department);
return View(employees.ToList());
}
[HttpGet]
public ActionResult CreateEmployee()
{
SelectList EmpList = new SelectList(db.Departments, "Id", "Name");
ViewBag.EmpList = EmpList;
return View();
}
[HttpPost]
public ActionResult CreateEmployee(Employee employee, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
employee.Foto = data;
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
Представление Index
:
@model IEnumerable<EmployeeBase.Models.Employee>
@{
ViewBag.Title = "Company";
}
<h2>ООО "Моя Компания"</h2>
<p>
<a href="/Home/CreateEmployee">
<input type="button" value="New" />
</a>
</p>
<table border="1">
<tr>
<th>Name</th>
<th>Birth</th>
<th>Foto</th>
<th>Department</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.BirthDate)</td>
<td>@Html.DisplayFor(modelItem => item.Foto)</td>
<td>@Html.DisplayFor(modelItem => item.Department.Name)</td>
<td>
<a href="/Home/EditEmployee/@item.Id">
<input type="button" value="Edit" />
</a>
</td>
<td>
<a href="/Home/DeleteEmployee/@item.Id">
<input type="button" value="Delete" />
</a>
</td>
</tr>
}
</table>
Представление CreateEmployee
:
@model EmployeeBase.Models.Employee
@{
Layout = null;
}
<h2>Добавление нового сотрудника</h2>
<fieldset>
<legend>Сотрудник</legend>
@using (Html.BeginForm())
{
<table>
<tr>
<td>Name</td>
<td>@Html.EditorFor(modelItem => modelItem.Name)</td>
</tr>
<tr>
<td>Birth</td>
<td>@Html.EditorFor(modelItem => modelItem.BirthDate)</td>
</tr>
<tr>
<td>Foto</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td>Department</td>
<td>@Html.DropDownListFor(modelItem => modelItem.DepartmentId, ViewBag.EmpList as SelectList)</td>
</tr>
</table>
<input type="submit" value="Add" />
}
</fieldset>