Hi comunidadmexi...,
Using this article i have created the example.
Check this example. Now please take its reference and correct your code.
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
FilesEntities entities = new FilesEntities();
return View(entities.Files.ToList());
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile, string name)
{
string fileName = name, filePath = "";
if (postedFile != null)
{
fileName = System.IO.Path.GetFileName(postedFile.FileName);
filePath = "~/Uploads/" + fileName;
postedFile.SaveAs(Server.MapPath(filePath));
}
FilesEntities entities = new FilesEntities();
entities.Files.Add(new File { Name = fileName, Path = filePath });
entities.SaveChanges();
return RedirectToAction("Index");
}
}
View
@model IEnumerable<WebGrid_Image_Path_Database_EF_MVC.File>
@{
Layout = null;
WebGrid webGrid = new WebGrid(source: Model, canSort: false, canPage: false);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<span>Name : </span><input type="text" name="name" value="" /><br />
<input type="file" name="postedFile" />
<input type="submit" id="btnUpload" value="Upload" />
}
<hr />
@webGrid.GetHtml(
htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
columns: webGrid.Columns(
webGrid.Column("FileId", "Image Id"),
webGrid.Column("Name", "Name"),
webGrid.Column("Path", "Image",
format: @<text>
@if (string.IsNullOrEmpty(item.Path))
{
<img alt='No Image' src='@Url.Content("~/Images/NoImage.png")' />
}
else
{
<img alt='@item.Name' src='@Url.Content(item.Path)' />
}
</text>
)
)
)
</body>
</html>
Screenshot