I'm trying to do a movie gallery in MVC, and I have the following algorithm:
Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(archivo.FileName));
<img src="/Images/@MovieGallery.Imagen"/>
using a foreach loop.(Please correct me if my algorithm is not good)
And this is my code:
Controller
[HttpPost]
public ActionResult Peliculas_Agregar(pelicula pelis) {
string path="";
HttpPostedFileBase archivo = Request.Files["Imagen"]; // @name= file, capturo el name
if (ModelState.IsValid) { // Validar si son validos los campos segun DBSET
try
{
if (archivo != null && archivo.ContentLength > 0) { //El nombre del archivo debe ser mayor que 0 y no debe ser nulo
try
{
path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(archivo.FileName));
archivo.SaveAs(path);
}
catch (Exception ex) {
ViewBag.ErrorArchivo = ex;
}
}
Cine.peliculas.Add(pelis);
Cine.SaveChanges();
}
catch (Exception ex){
ViewBag.Error = ex;
}
}
return View(pelis);
}
Model (Generated by Entity Framework)
public int id_peli { get; set; }
public string titulo { get; set; }
public string director { get; set; }
public string cast { get; set; }
public string descripcion { get; set; }
public Nullable<int> duracion { get; set; }
public string categoria { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Cargar imagen")]
//[Required(ErrorMessage = "Por favor carga una imagen")]
public string imagen { get; set; } // here is where i want to save files name, not the path.
View
@using (Html.BeginForm("Peliculas_Agregar", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="Formas">
<div class="form-group">
@Html.LabelFor(m => m.titulo, new { htmlAttributes = new { @for = "exampleTittle" } })
@Html.EditorFor(m => m.titulo, new { htmlAttributes = new { @placeholder = "Título", @class = "form-control"} })
</div>
<div class="form-group">
<input type="file" name="Imagen" />
</div>
</div>
<input type="submit" value="Agregar Película" class="btn btn-outline-primary" />
}
My code works OK, but the main problem that I am facing is that I can't or I don't know how to save the image name to database because I'm not getting the string name of the image that is coming into the parameter. I'm just getting a string or type called like System.Web.HttpPostedFileWrapper : System.Web.HttpPostedFileWrapper
I think this is because I am using HttpPostedFileBase to save the image into the server but I can't edit this and save just the image name into the server. Can't do both things. How could I solve this?
Following the two liked answers we use a View Model to post the form and file. Then we map the VM fields to the Entity's fields before performing the database actions.
Entity Model
public class Movie
{
public string Title { get; set; }
public string FileName { get; set; }
}
Create a View Model to capture your form values
public class MovieVM
{
public string Title { get; set; }
[Display(Name = "Upload Image")]
public HttpPostedFileBase Image { get; set; }
}
The action accepts the MovieVM instead of the Entity
[HttpPost]
public ActionResult UploadMovie(MovieVM model)
{
if (ModelState.IsValid)
{
// save file
// ...
// Map to Entity to save to db
Movie movie = new Movie
{
Title = model.Title,
FileName = model.Image.FileName
};
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Success");
}
return View(model);
}