简体   繁体   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?

I have an MVC 5 application that need to import the data of an Excel file in a database table. 我有一个MVC 5应用程序,需要将Excel文件的数据导入数据库表中。 The ActionResult, receive two parameters, the Excel file, and the idEmbarque (a vessel shipment id). ActionResult接收两个参数,即Excel文件和idEmbarque(船只装运ID)。 The problem is with the first parameter, named "archivoExcel" it's value is null. 问题在于第一个参数名为“ archivoExcel”,其值为空。

This are the Actions Results "ImportarLista" (HttpGet and HttpPost) in the "ListaDespachoControler": 这是“ 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"); } 

The parameters in the HttpGet Action Result comes from a View named Index, and is used to display information in the "ImportrarLista" View. HttpGet操作结果中的参数来自名为Index的视图,用于在“ ImportrarLista”视图中显示信息。

This is the "ImportarLista View code: 这是“ 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> } 

Then when I click in the submit button, the HttpPost ActionResult don't have any file in the first parmameter. 然后,当我单击“提交”按钮时,HttpPost ActionResult在第一个参数中没有任何文件。 It's null. 是空的

BTW, for additional information, if I use: FormMethod.Post in the use of @using call like this: 顺便说一句,有关其他信息,如果我使用的话:FormMethod.Post在使用@using调用时是这样的:

@using (Html.BeginForm("ImportarLista", "ListaDespacho",FormMethod.Post, new { enctype = "multipart/form-data", idEmbarque = Model.CodigoEmbarque })) @using(Html.BeginForm(“ ImportarLista”,“ ListaDespacho”,FormMethod.Post,新的{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. 我遵循在网站上找到的两个示例,但是在“ archivoExcel”参数中继续使用空值。

I will apreciate your help. 我会感谢您的帮助。

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

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

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

相关问题 将多部分/表单数据发布到端点 - Post multipart/form-data to endpoint VBA发布请求错误-多部分/表单数据 - VBA post request error - multipart/form-data 从 ASP.NET Core HttpContext.Request 的 multipart/form-data 内容读取 excel 文件? - Reading excel file from ASP.NET Core HttpContext.Request of multipart/form-data content? 如何使用Power Query的Web发布目录/表单数据 - How to POST a multipart/form-data using Power Query's Web.Contents 如何使用python中的POST请求在multipart/form-data中发送excel文件? - How to send excel file in multipart/form-data with POST Requests in python? Powershell:如何在多部分/表单数据请求中发布 excel (.xlsx) 文件? - Powershell: How can I POST excel (.xlsx) files in a multipart/form-data request? 为什么我的ListBox8.value列为Null? - Why is my ListBox8.value listed as Null? 为什么我的 WorkbookView 序列使用 OpenXml 不断返回“null”值? - Why does my WorkbookView sequence keep returning “null” value with OpenXml? VBA POST请求发送包含上载文件的多部分表单数据 - VBA POST request sending multipart form data with uploading file 如何使用 WinHTTPRequest 在 Excel 中使用 VBA 发送表单数据 POST 请求 - How to send a form-data POST request with VBA in Excel using WinHTTPRequest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM