Method to edit does not work ASP.NET MVC 5

0

I am working in a web application of a car dealership, I have a view to edit the object of type Automovil that has the following parameters: model, year of manufacture, color, price, transmission, fuel, brand, model, category , state, extra and photo.

I generated my controller using MVC and Entity Framework, however, it does not modify any of the data, it only modifies the photo.

Method to edit

[HttpPost, ActionName("Edit")]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Automovil automovil, HttpPostedFileBase archivo)
    {
        if(automovil ==null){
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        if (TryUpdateModel(automovil, "", new string[] { "idAutomovil,modelo,año,color,precio,informacionExtra,idMarca,idCategoria,idCombustible,idEstado,idTransmision" }))
        {
            try
            {
                if(archivo != null && archivo.ContentLength > 0)
                {
                    if(automovil.archivos.Any(i => i.tipo == FileType.Imagen))
                    {
                        db.archivo.Remove(automovil.archivos.First(i => i.tipo == FileType.Imagen));
                    }
                    var imagen = new Archivo
                    {
                        nombre = System.IO.Path.GetFileName(archivo.FileName),
                        tipo = FileType.Imagen,
                        ContentType = archivo.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(archivo.InputStream))
                    {
                        imagen.contenido = reader.ReadBytes(archivo.ContentLength);
                    }
                    automovil.archivos = new List<Archivo> { imagen };
                }
                db.Entry(automovil).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch(RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.)
                ModelState.AddModelError("", "Unable to save changes. Try again and if the problem persists, see your system administrator.");
            }
        }
        ViewBag.idCategoria = new SelectList(db.categoria, "idCategoria", "nombre", automovil.idCategoria);
        ViewBag.idCombustible = new SelectList(db.combustible, "idCombustible", "nombre", automovil.idCombustible);
        ViewBag.idEstado = new SelectList(db.estado, "idEstado", "nombre", automovil.idEstado);
        ViewBag.idMarca = new SelectList(db.marca, "idMarca", "nombre", automovil.idMarca);
        ViewBag.idTransmision = new SelectList(db.transmision, "idTransmision", "nombre", automovil.idTransmision);
        return View(automovil);
    }

As I mentioned before, the only thing that edits me is the image of the car, not the other data.

Debugging the program I could notice that when editing some Automobile fields they appear as null.

Debug

I would be grateful if you could help me to see what I have to correct in my controller to receive that data.

EDIT

Vista Code

@model Autoventas_IN6AV.Models.Automovil

@{
    ViewBag.Title = "Editar";
}

<h2>Editar Información</h2>


@using (Html.BeginForm("Edit", "Automovil", null, FormMethod.Post, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Automovil</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.idAutomovil)

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

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

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.idMarca, "Marca", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idMarca", String.Empty)
                @Html.ValidationMessageFor(model => model.idMarca)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.idCategoria, "Categoria", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idCategoria", String.Empty)
                @Html.ValidationMessageFor(model => model.idCategoria)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.idCombustible, "Combustible", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idCombustible", String.Empty)
                @Html.ValidationMessageFor(model => model.idCombustible)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.idEstado, "Estado", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idEstado", String.Empty)
                @Html.ValidationMessageFor(model => model.idEstado)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.idTransmision, "Transmisión", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idTransmision", String.Empty)
                @Html.ValidationMessageFor(model => model.idTransmision)
            </div>
        </div>

        @if (Model.archivos.Any(i => i.tipo == FileType.Imagen))
        {
            <div class="form-group">
                    <span class="control-label col-md-2"><strong>Foto Actual</strong></span>
                    <div class="col-md-10">
                        <img src="~/Archivo/[email protected](i => i.tipo == FileType.Imagen).idArchivo" alt="Imagen Automóvil."/>
                    </div>
            </div>
        }

        <div class="form-group">
            @Html.Label("Foto", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" id="Imagen" name="archivo" />
            </div>
        </div>

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

<div>
    @Html.ActionLink("Regresar al listado", "Index")
</div>

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

EDIT

Model Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Autoventas_IN6AV.Models
{
    public class Automovil
    {
        [Key]
        public int idAutomovil { get; set; }
        [Display(Name = "Modelo"), Required(ErrorMessage = "Este dato es obligatorio.")]
        public String modelo { get; set; }
        [Display(Name = "Año de Fabricación"), Required(ErrorMessage = "Este dato es obligatorio.")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy}", ApplyFormatInEditMode = true)]
        public DateTime año { get; set; }
        [Display(Name = "Color"), Required(ErrorMessage = "Este dato es obligatorio.")]
        public String color { get; set; }
        [Display(Name = "Precio"), Required(ErrorMessage = "Este dato es obligatorio."), DataType(DataType.Currency)]
        public String precio { get; set; }
        [Display(Name = "Extras"), Required(ErrorMessage = "Este dato es obligatorio.")]
        public String informacionExtra { get; set; }

        public int idMarca { get; set; }
        public virtual Marca marca { get; set; }

        public int idCategoria { get; set; }
        public virtual Categoria categoria { get; set; }

        public int idCombustible { get; set; }
        public virtual Combustible combustible { get; set; }

        public int idEstado { get; set; }
        public virtual Estado estado { get; set; }

        public int idTransmision { get; set; }
        public virtual Transmision transmision { get; set; }

        public virtual Reservacion reservacion { get; set; }

        public virtual List<Archivo> archivos { get; set; }

    }
}
    
asked by José Carlos Loarca Hass 06.04.2016 в 04:37
source

1 answer

2

Depending on your model, this is normal. From the view you will only receive the id of the related entities, there is no problem that for example combustible is null as long as idCombustible is assigned. Entity Framework will update the entity correctly if one of the two properties is assigned. MVC does not automatically load related entities by id, it does not have information to know how.

There is also an error in the TryUpdateModel line, the value:

Bad :

new string[] { "idAutomovil,modelo,año,color,precio,informacionExtra,idMarca,idCategoria,idCombustible,idEstado,idTransmision" }

Correct :

new string[] { "idAutomovil", "modelo", "año", "color", "precio", "informacionExtra", "idMarca", "idCategoria", "idCombustible", "idEstado", "idTransmision" }
    
answered by 06.04.2016 / 07:00
source