I'm trying to upload my images in a folder and i'm trying to put the imagepath in my database. But I can't get my input file in asp.net mvc. How can I fix this and how can I call the input file in my Controller?
Create.cshtml
@model SecundaireSchool.Models.tblLeraren
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm(new { enctype= "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>tblLeraren</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.naam, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.naam, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.naam, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.emailadres, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.emailadres, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.emailadres, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.foto, "test" , htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.foto, "test" , new { type = "file", @class = "input-file", @name = "file" })
</div>
</div>
<!-- <div class="form-group">
@@Html.LabelFor(model => model.foto, htmlAttributes: new { @@class = "control-label col-md-2" })
<div class="col-md-10">
@@Html.EditorFor(model => model.foto, new { htmlAttributes = new { @@class = "form-control" } })
@@Html.ValidationMessageFor(model => model.foto, "", new { @@class = "text-danger" })
</div>
</div> -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
TeacherController
So i succeeded to insert the image path to my db. But it doesn't add it in my image folder. What am I doing wrong?
[HttpPost]
public ActionResult Create(tblLeraren teacher, HttpPostedFileBase file = null)
{
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
teacher.foto = path;
}
db.tblLerarens.Add(teacher);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(teacher);
}