I cannot upload image in my MVC application. Does anyone know how I can fix this error?
Model Image:
namespace HelloWorld.Models
{
public class Image
{
[Required]
[DataType(DataType.MultilineText)]
public string ImagePath { get; set; }
public int ImageId { get; set; }
}
}
Index view:
@model IEnumerable<HelloWorld.Models.Image>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
@foreach (var item in Model) {
<img src="@Html.DisplayFor(modelItem => item.ImagePath)">
}
Create view:
@model HelloWorld.Models.Image
@{
ViewBag.Title = "Create";
}
<form method="post" action="@Url.Action("Create", "Images")">
<div>
<h4>Image</h4>
<hr />
<input type="file" name="file">
<input type="submit" value="Upload">
</div>
</form>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Create action:
[HttpPost]
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("../../Content/img/upload/") + file.FileName);
img.ImagePath = file.FileName;
}
db.Images.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Create","Images");
}
I think my problem is that I have model state not valid. Because I have RedirectToAction("Create","Images");