I am doing a project in that I am adding an image and a text.I have given an image and text and that works perfectly. but when I change the text only the image got deleted and only the text seems to appear.
controller
public async Task<ActionResult> StudentList(Student student, HttpPostedFileBase Img)
{
if (Img != null)
{
var imageTypes = new string[]{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
};
if (Img.FileName == null || Img.ContentLength == 0)
{
ModelState.AddModelError("Images", "This field is required");
}
else if (!imageTypes.Contains(Img.ContentType))
{
ModelState.AddModelError("Images", "Please choose either GIF, JPG or PNG image.");
}
if (ModelState.IsValid)
{
if (Img != null)
{
var fileName = Path.GetFileName(Img.FileName);
var directoryToSave = Server.MapPath(Url.Content("~/Images"));
var pathToSave = Path.Combine(directoryToSave, fileName);
Img.SaveAs(pathToSave);
student.Images = fileName;
}
db.Entry(student).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("StudentList", "Students", new { @id = 2 });
}
}
else
{
if(ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("StudentList", "Students", new { @id = 2 });
}
}
return View(student);
}
view
<div class="form-group">
@Html.LabelFor(model => model.Images, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="editor-field">
@Html.DisplayTextFor(model => model.Images)
@Html.TextBoxFor(m => m.Images, new { type = "file" })
</div>
</div>
@Html.ValidationMessageFor(model => model.Images, "", new { @class = "text-danger" })
</div>
I don't know why this happends, when I just click the save button the image get deleted. In the
@Html.DisplayTextFor(model => model.Images)
field it will get the image name but it is not passing to the httpPost method StudentList action method. why is this happening ?? how can I change text without deleting image??
can anyone please help me to find the solution ?
What I have tried:
Have searched many times but can't fix this error.