Доброго, не судите строго, в asp.net я новичок. Есть форма
@model BooksCatalogue.Models.booksCatalogue
@{
ViewBag.Title = "Create";
}
<h2>Новая книга</h2>
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr/>
<table width="100%">
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<tr>
<td width="10%" valign="top">
<div class="form-group">
<div class="col-md-10">
<img id="show" src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAMAAABCfAldAAAAJ1BMVEX////i4uLk5OT4+Pjg4ODy8vL8/Pzt7e35+fno6Ojw8PD19fXq6urZKFYqAAAD20lEQVR4nO2a2XKDMAxFifGK/f/fWwJesUSSFpl0RucpQ0l9ox3jaWIYhmEYhmEYhmGYf4H1Xq14r+9W0qGtcg8pHxEpRVD2a2Rqb8QDwC3zN2i0i4PUbax2vFuiXkDjVWZUt8pTL+RtZvS36Zsb5wrnQjArIbhWd7jJz7X51mjzOW21nn0Tme4WI4a8vnRKd0bStgpPsQyXp/PqArdPsbEMI8VNdfiFszTVxdNjA9GmdcWrQmfNHQp10ufm1zerpNDQC0uIj5ZM4SCHKTQfmiQZXA6qNsln75cOHUuSeCMi/o4Vn4dUsuGIREnW+CygksIBBdvH/K2uoI5TNn+co5Mtdu9liGM0eYGFlqpdGiOXvKMoeXDVLLDgfzY6lxWm0CCOwtiCi2XmTTA08+0mE+VOMcKEcdWsx8eU7hWmYuRy1JkBURj9lDPElpnm4OXc4Iq1owlJEzmukc2l8yhwUFgNs2XaCfS1MNqlulIp9N19zY9Z7Y3G61VEDzc1GlJY9IlmWiT3cczhxpmAlzF900LtY7/5yLULdArB+Nuw+110Ak3v4XI5eRmOv/23bB1Z0s00DjJLq3BG/fskIP/gKgRol9bL4kRfDEK6yVrWqYAoxOJvYx+FHPCXS9B7joC9qlMIVru9MwoqgRZKYlgh5N8pdyJagUgZa7yM6KMWOJ8JrDdr0GaxC5RUAk8tWNc/tN/eKXBpYxBWSOxifZIk6tECPwUQZ/GEl5l+LxhUSFwHJ3Tl4t9q0xJ9TqHrJFgvrvQpeIKNGOQfXAUyzbTzAfYUMOVphm6kBufB4/yHPqesf9ov082DcYE2S6r6Ek2Denk3NeFEHbeAmj5Rx1+6hikEvn4xu5q6joHzKeJl3diZhL3QyuJj5PkDVrj/PGQauobjzsJc9B3sUhRmQXEbgnan+rg3kyzYz1dJYbHgAmb2xXS7Wx7Rl7xc9Nghu1vJMMWh6hh/jcIqi/dvEj5zRqLjSp6siYPkpWluk234ktFv5Sq0t5piLt1tHVPxy/36X70b+B0ey9szYujCj6xXE5vbJ/t85vOv/IH8YutdG6a+Ike9d89v299TaNPzKH0GJ3xqY+aNvppffpM24QPp7cPrsqHzuDNSX6XwYc4kah/SibMxCVwoc4ww6NI+iHvs96SatBCJlbxbDh/V21lSmFmXwz3rRx8esvyCm06YtdsJwoVF+echzCW0J/beORtCgwV2fjteHq0hZXbyXJ7EU2iUxNDtG1XWe6eSk2MXB2r8ggOiCT0rI6qsXT8647/iiG1BryoXE1bMsmr7LnEMwzAMwzAMwzAM80/5AZO5F89XG1jOAAAAAElFTkSuQmCC width="170" height="170"/>
</div>
</div>
</td>
<td width="40%" valign="top">
<div class="form-group">
@Html.LabelFor(model => model.title, "Название", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.title, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.title, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.author, "Автор", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.author, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.author, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.genre, "Жанр", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.genre, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.genre, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.cover, "Обложка", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
<input id="files" type="file" accept=".jpg" name="files" />
@Html.ValidationMessageFor(model => model.cover, "")
<script>
function handleFileSelect(evt) {
var reader = new FileReader();
var file = evt.target.files;
var img = document.getElementById('show');
reader.onload = function (e) { img.src = e.target.result };
reader.readAsDataURL(evt.target.files[0]);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</div>
</div>
</td>
<td width="50%" valign="top">
<div>
<div class="form-group">
@Html.LabelFor(model => model.description, "Аннотация", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.description, "", new { @class = "text-danger" })
</div>
</div>
</div>
</td>
</tr>
</table>
<table width="100%">
<tr>
<td width="10%"></td>
<td width="90%">
<div class="form-group">
@Html.LabelFor(model => model.contents, "Содержание", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.contents, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.contents, "", new { @class = "text-danger" })
</div>
</div>
</td>
</tr>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="sbmt" type="submit" value="Добавить книгу" class="btn btn-default"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Вернуться", "Index")
</div>
и есть контролер (пока решил не заморачиваться и сделал один для всех форм). Форму добавления новой книги обрабатывают два метода
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection, HttpPostedFile files)
{
var path = "";
if (files != null && files.ContentLength > 0)
{
string filename = "createimage.jpg";
path = Path.Combine(Server.MapPath("~/App_Data"), filename);
files.SaveAs(path);
}
try
{
var context = new CatalogueEntities();
context.booksCatalogue.Add(new booksCatalogue
{
id = context.booksCatalogue.Count() + 1,
author = collection["author"],
contents = collection["contents"],
cover = System.IO.File.ReadAllBytes(path),
description = collection["description"],
genre = collection["genre"],
title = collection["title"]
});
context.SaveChanges();
System.IO.File.Delete(path);
return RedirectToAction("Index");
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation(
"Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
return View();
}
}
Внимание, вопрос)) Что я делаю не так? Метод public ActionResult Create(FormCollection collection, HttpPostedFile files) не перехватывает files(всегда null). Мне кажется что проблема в самой форме, но в чем именно она заключается не мог никак понять. Замечу, что необходимо загружать фото именно при нажатии на кнопку "добавить", дополнительных форм быть тоже не должно. Благодарствую за внимание, господа)