繁体   English   中英

为什么带有multipart / form-data的HttpPost的ActionResult在“ archivoExcel”参数中接收空值?

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

我有一个MVC 5应用程序,需要将Excel文件的数据导入数据库表中。 ActionResult接收两个参数,即Excel文件和idEmbarque(船只装运ID)。 问题在于第一个参数名为“ archivoExcel”,其值为空。

这是“ ListaDespachoControler”中的操作结果“ ImportarLista”(HttpGet和HttpPost):

  // 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"); } 

HttpGet操作结果中的参数来自名为Index的视图,用于在“ ImportrarLista”视图中显示信息。

这是“ ImportarLista查看代码:

 @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> } 

然后,当我单击“提交”按钮时,HttpPost ActionResult在第一个参数中没有任何文件。 是空的

顺便说一句,有关其他信息,如果我使用的话:FormMethod.Post在使用@using调用时是这样的:

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

我收到“页面加载错误”的错误。 因此,我不在通话中使用这些。 我遵循在网站上找到的两个示例,但是在“ archivoExcel”参数中继续使用空值。

我会感谢您的帮助。

谢谢! -阿里斯蒂德斯·佩拉尔塔(Aristides Peralta)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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