I'm trying to upload images to my application. I did a prototype of upload, only it does not show the image, but the ID or NAME of it. And I'm uploading to a folder I've created in my project.
My questions are:
How do I show this image?
In the project I'm really working on, I need to show this image to the user because it's a school and needs to have the student's picture. I even created the student's registration;
How do I link this photo to the student's record?
Should I create a student model and another image model, or have some other form?
And what is the best way to upload, by recording the image in the bank or in a folder in the project?
Here are my prototype codes:
Image.cs (Model)
public partial class Imagem
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
ImageController.cs (Controller, and here only has the part of create)
public ActionResult Create()
{
return View();
}
// POST: /Imagem/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Imagem img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Imagens/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Imagems.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Index.cshtml (a View)
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ID)
@* <img src="@Url." alt="Image" width="300px" /> *@
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new {id = item.ID})
</td>
</tr>
}
</table>
Create.cshtml (Another View)
@using (Html.BeginForm("Create", "Imagem", null, FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}