I am working on a project in which I have to make a CV builder. I am using the same form to edit and insert. Edit returns the same Index method but with the particular information about that Id.
My issue is that I don't know how to bind that particular image in input type=" file" and I always run into the condition of "Please Choose an Image".
All the images are saved in the Images folder that I've created in the project.
Screen shots When I am browsing and choosing an Image When I return View with specific information about that Id
Razor View
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data", id = "quickForm" }))
{
<div class="col-md-4">
<!-- Image Upload -->
<div class="container">
<div class="avatar-upload">
<div class="avatar-edit">
<input type='file' name="File" id="File" src="@(Model.ImagePath != null && File.Exists(Server.MapPath(Model.ImagePath)) ? Server.MapPath(Model.ImagePath) : Url.Content("~/Content/Images/Default_Image.png" ))" accept=".png, .jpg, .jpeg" required />
<label for="File"></label>
</div>
<div class="avatar-preview" style="width:100%;height:13em">
<div id="imagePreview" style="background-image: url('@(Model.ImagePath != null && File.Exists(Server.MapPath(Model.ImagePath)) ? Url.Content(Model.ImagePath) : Url.Content("~/Content/Images/Default_Image.png" ))');">
@*../../Content/Images/Default_Image.png*@
</div>
</div>
</div>
<h1>
Image Upload
<small>.png, .jpg, .jpeg</small>
</h1>
</div>
</div>
}
I am setting the source of File through JQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').css('background-image', 'url(' + e.target.result + ')');
$('#imagePreview').hide();
$('#imagePreview').fadeIn(650);
$('#File').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#File").change(function () {
readURL(this);
});
Model Class
public class BasicInformation
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(150)]
public string ImageTitle { get; set; }
[StringLength(150)]
public string ImagePath { get; set; }
[NotMapped]
public HttpPostedFileBase File { get; set; }
}
Controller Method
public ActionResult Index(int? id)
{
BasicInformation info = db.BasicInformation.Find(id);
if (info != null)
{
return View(info);
}
else
{
BasicInformation information = new BasicInformation();
return View(information);
}
}