MVC Upload Image and send the database

Asked

Viewed 370 times

0

Good evening I’m making an online shop for a discipline and I was wondering if someone could help me create the image upload to the Database.

The purpose is to add in the admin page and appear in the index.

Page where the product is created:

    @model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Adicionar Novo Filme";
}

<h2>Adicionar Novo Filme</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Filme</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        <label class="control-label col-md-2" for="Titulo">Titulo</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="ReleaseDate">Data de Lançamento</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ReleaseDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Genero">Género</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Genre, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Preco">Preço</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Img">Imagem</label>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Img, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Img, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Adicionar" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The Controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();


        public ActionResult Index(string movieGenre, string searchString)
        {
            var GenreLst = new List<string>();

            var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;

            GenreLst.AddRange(GenreQry.Distinct());
            ViewBag.movieGenre = new SelectList(GenreLst);

            var movies = from m in db.Movies
                         select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                movies = movies.Where(s => s.Title.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(movieGenre))
            {
                movies = movies.Where(x => x.Genre == movieGenre);
            }


            return View(movies);
        }

        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Img")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }


        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Img")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Entry(movie).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(movie);
        }


        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Movie movie = db.Movies.Find(id);
            db.Movies.Remove(movie);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }


    }
}

The database is:

CREATE TABLE [dbo].[Movies] (
    [ID]          INT            IDENTITY (1, 1) NOT NULL,
    [Title]       NVARCHAR (MAX) NULL,
    [ReleaseDate] DATE           NOT NULL,
    [Genre]       NVARCHAR (MAX) NULL,
    [Price]       MONEY          NULL,
    [Img] IMAGE NULL, 
    CONSTRAINT [PK_dbo.Movies] PRIMARY KEY CLUSTERED ([ID] ASC)
);
  • Leadnnd, did you ever look at that question? https://answall.com/questions/14285/upload-images

  • @Leadnndpereira The only difference is that in this case, the upload is not saved in the database but in a directory (which is the most appropriate one). Unless it is a requirement to save the contents of the file in the database, I would recommend you to follow Ricardo Pontual’s instructions

  • It would really take the storage in the database to appear on the main page more easily because you wouldn’t notice the folder.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.