0

I have an MVC 5 application that need to import the data of an Excel file in a database table. The ActionResult, receive two parameters, the Excel file, and the idEmbarque (a vessel shipment id). The problem is with the first parameter, named "archivoExcel" it's value is null.

This are the Actions Results "ImportarLista" (HttpGet and HttpPost) in the "ListaDespachoControler":

 // GET: /ListaDespacho/ImportarLista/
        public ActionResult ImportarLista(int? id, string barco, string numeroAZ)
        {
            ListaDespachoViewModels model = new ListaDespachoViewModels
            {
                CodigoEmbarque = (int)id,
                NombreDelBarco = barco,
                NumeroAZ = numeroAZ
            };

            return View(model);
        }

     
        // POST: /ListaDespacho/ImportarLista        
        [HttpPost]     
        public ActionResult ImportarLista(HttpPostedFileBase archivoExcel, int idEmbarque)
        {
            try
            {
                // Codigo del embarque seleccionado de la lista
                int _codigoEmbarque = idEmbarque;

                if (archivoExcel != null)
                {

                    if (archivoExcel.ContentLength > 0)
                    {
                        string fileExtension =
                                             System.IO.Path.GetExtension(Request.Files["archivoExcel"].FileName);

                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            string fileLocation = Server.MapPath("~/Content/") + Request.Files["archivoExcel"].FileName;
                            if (System.IO.File.Exists(fileLocation))
                            {

                                System.IO.File.Delete(fileLocation);
                            }
                            Request.Files["archivoExcel"].SaveAs(fileLocation);
                        }
                    }

                    // Si ya existe el embarque en la lista de despachos, se elimina 
                    // para insertar nuevamente los datos.

                    // buscar embarque en lista de despacho
                    var lDsp = (from ld in _db.ListaDespachos
                                where ld.EmbarqueId == _codigoEmbarque
                                select ld);

                    _db.ListaDespachos.RemoveRange(lDsp);
                    _db.SaveChanges();

                    // Incluir datos               
                    string usuario = User.Identity.GetUserName().ToString();

                    var excel = new ExcelQueryFactory();
                    excel.FileName = @"C:\ImEx\Hojas_Excel\LISTA DESPACHO.xlsx";
                    excel.TrimSpaces = LinqToExcel.Query.TrimSpacesType.Both;
                    excel.StrictMapping = LinqToExcel.Query.StrictMappingType.WorksheetStrict;

                    var listaDespachoExcel = from ld in excel.Worksheet<ListaDespachoExcel>() select ld;

                    if (listaDespachoExcel.Count() > 0)
                    {
                        foreach (var detalle in listaDespachoExcel)
                        {
                            //string _prefijo = detalle.Prefijo;
                            //string _numeroContenedor = detalle.NumeroContenedor;
                            if (detalle.Prefijo != null)
                            {
                                var listaDespachos = new List<ListaDespacho>
                            {
                               new ListaDespacho{Prefijo = detalle.Prefijo,
                                                 NumeroContenedor = detalle.NumeroContenedor.ToString(),
                                                 Tamanio = detalle.Tamanio,
                                                 Peso = detalle.Peso,
                                                 Viaje = detalle.Viaje,
                                                 FullEmpty = (bool)detalle.FullEmpty,
                                                 NumeroMarchamo = detalle.NumeroMarchamo.ToString(),
                                                 Ubicacion = detalle.Ubicacion.ToString(),

                                                 EmbarqueId = _codigoEmbarque,   
                                                 AudFecha = DateTime.Now,
                                                 AudUsuario = usuario }
                            };
                                listaDespachos.ForEach(s => _db.ListaDespachos.Add(s));
                            }
                        }
                        // Guardar cambios 
                        _db.SaveChanges();
                    }
                    else
                    {

                        return View("ImportarListaError");
                    }
                    return View("ImportarListaExito");
                }              
                else
                {

                    return View("ImportarListaError");
                }

            }
            catch (FormatException ex)
            {
                RedirectToAction("Error", ex);
                
            }
            catch (Exception ex)
            {
                RedirectToAction("Error", ex);

            }


            return RedirectToAction("Index");

        }

The parameters in the HttpGet Action Result comes from a View named Index, and is used to display information in the "ImportrarLista" View.

This is the "ImportarLista View code:

@model jodef.ImEx.Models.ListaDespachoViewModels

<!--Se utiliza un modelo de vista, para regresar el codigo de embarque a la acción
    que procesa la inclusión de los datos de la hoja Excel. Se hace necesario
    enviar el código del embarque para identificar cada registro de que se
    incluya de la lista de despacho con el embarque seleccionado-->

<div class=" ui-grid-a">
    <div class=" ui-bar ui-bar-c">Importar Lista de Despacho</div>
</div>

@using (Html.BeginForm("ImportarLista", "ListaDespacho", new { enctype = "multipart/form-data", idEmbarque = Model.CodigoEmbarque }))
{
    @Html.AntiForgeryToken()

    <div class=" ui-grid-solo" style="margin-left:20%">
        <div class=" ui-grid-a">
            <div class=" ui-block-a">
                @Html.ValidationSummary()
            </div>
        </div>

        <div class=" ui-grid-a">
            <div class=" ui-block-a" style="width:18%">
                <h5>Nombre del Barco: </h5>
            </div>
            <div class=" ui-block-b" style="color:#ff6a00">
                <h5 style="font-weight: bold">@Model.NombreDelBarco</h5>
            </div>

            <div class=" ui-block-a" style="width:18%">
                <h5>Numero A-Z: </h5>
            </div>
            <div class=" ui-block-b" style="color:#ff6a00">
                <h5 style="font-weight: bold">@Model.NumeroAZ</h5>
            </div>
        </div>

        <div class="ui-grid-a" style="margin-top:2%">
            <div class="ui-block-a">
                <div>
                    <h6>
                        Seleccione el archivo Excel que contiene la lista de Contenedores a
                        despachar para el embarque, de la carpeta <b>(C:\ImEx\Hojas_Excel)</b>.
                    </h6>
                </div>
                <div>
                    <h6>
                        Para iniciar el proceso de importación de datos, haga click en el botón "Importar datos".
                    </h6>
                </div>
            </div>
            <div class=" ui-block-a" style="width:40% ">
                <div>
                    <input name="archivoExcel" type="file" />
                </div>
                <div style=" margin-top:4%"> 
                    <input type="submit" value="Importar Datos" class="ui-btn ui-shadow ui-corner-all " />
                </div>
            </div>
        </div>
    </div>
}

Then when I click in the submit button, the HttpPost ActionResult don't have any file in the first parmameter. It's null.

BTW, for additional information, if I use: FormMethod.Post in the use of @using call like this:

@using (Html.BeginForm("ImportarLista", "ListaDespacho",FormMethod.Post, new { enctype = "multipart/form-data", idEmbarque = Model.CodigoEmbarque }))

I receive an error of "page loading error". So, I don't use these in the call. I follow the two examples I found in the site, but, continue with a null value in the "archivoExcel" parameter.

I will apreciate your help.

Thank you! -Aristides Peralta

1 Answer 1

0

I would have liked to comment, but i cant :( shouldnt novice be allowed to comment and others to answer? anyway! when using the form post, I think it is important to have FormMethod.Post. If you are not doing this, are you still able to get the view point to the [HttpPost] function ? If yes I think it might be something to do with binding. Probably the view is not bounded and you might want to update your core libraries.

3
  • Thank you for your answer Pramod. In releation to the behavior of the HttpPost, this is exactly the point. YES, The [HttpPost] ActionResult is excecuted, even if I don't use the FormMethod.Post parameter in the @using(Html.BeginForm...) in the view as you can see, but, if I debug the HttpPost ActionResult or function, the first parameter (archivoExcel) is null. So I' can't have my Excel file.
    – Aristides
    Oct 22, 2014 at 15:00
  • In relation to the behavior of the HttpPost, this is exactly the point. YES, The [HttpPost] ActionResult is executed, even if I don't use the FormMethod.Post parameter in the "@using(Html.BeginForm...)" in the view, as you can see, but, if I debug the HttpPost ActionResult or function, the first parameter (archivoExcel) is null. So I can't have my Excel file. Well, how can I update my core libraries, this libraries supouse to be updated at least with this version of VS Express for Web or they aren't at all? -Aris
    – Aristides
    Oct 22, 2014 at 15:07
  • I just update the Microsoft ASP.NET Web API 2.2 both client and core libraries but the problem persist.
    – Aristides
    Oct 23, 2014 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.