ASP .NET MVC Form with field "Image" - Load an image in the "View" and insert it into the DB

0

I have configured the connection to the database for the "Events" table

Which generates me the fields in the model, and in the Image field transforms it to type "byte"

    public byte[] Imagen { get; set; }

In the view I have the "Image" field configured in this way

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

How should I configure the field in the "View" so that when the image is attached and when I execute the "Create" method, the image is registered in SQL?

    
asked by Cristian F. Bustos 23.10.2017 в 02:48
source

1 answer

1

You must do several steps:

1) Create your form with the enctype="multipart / form-data" attribute and add an input element type file with the name attribute different from that of the Image property (See view code).

2) In your POST action method of the controller, create an HttpPostedFileBase parameter, with a name equal to the input, so that the field is mapped automatically. And finally convert the HttpPostedFileBase to an array of bytes. With this you then apply your BD logic.

This code will guide you.

public class HomeController : Controller {
    public ActionResult Imagen2() {
        return View();
    }

    [HttpPost]
    public ActionResult Imagen2(HttpPostedFileBase img, Evento evt) {
        using(var reader = new BinaryReader(img.InputStream)) {
            evt.Imagen = reader.ReadBytes(img.ContentLength);
        }

        // Aquí tu lógica de negocio y BD.

        return View();
    }
}

And your view (check the input and form elements):

@model MvcApp.Controllers.Evento
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Imagen2</title>
</head>
<body>
    @using (Html.BeginForm("Imagen2", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) {
        <div class="form-group">
            @Html.LabelFor(model => model.Imagen)
            <div class="col-md-10">
                @Html.TextBox("img", null, new {type = "file"})
                @Html.ValidationMessageFor(model => model.Imagen, "", new {@class = "text-danger"})
            </div>
        </div>
        <button>Enviar</button>
    }
</body>
</html>
    
answered by 08.01.2018 в 22:12