简体   繁体   中英

Why is my ActionResult with an HttpPost with multipart/form-data receiving a null value in the “archivoExcel” parameter?

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 AZ: </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

我本来想发表评论,但我不能:(无论如何,新手都不应该发表评论,其他人也可以回答吗?在使用表单发布时,我认为拥有FormMethod.Post很重要。如果您不这样做,您仍然能够将视点指向[HttpPost]函数?如果是,我认为这可能与绑定有关。该视图可能没有边界,您可能需要更新核心库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM