0

Mi duda es la siguiente: resulta que estoy pasando un archivo file por ajax al controlador y lo recibo sin ningún problema.

Pero aparte del file también quiero pasar un parámetro que es un id. que también tengo que recibirlo en el mismo controlador, en el ActionResult, recibo sin problemas el archivo pero no logro mandar el id. Alguna idea. es RAZOR con MVC .Net

Codigo ajax:

function Grabar(id,input_group_) {
            console.log("Entré a  grabar con " + id + " y " + input_group_);

          
            if (window.FormData !== undefined) {
                console.log("comenzare a buscar el archivo");
  
                var fileUpload = $(input_group_).get(0);  
                var files = fileUpload.files;  
              
                
                var fileData = new FormData();
                var id_query = id;

  
                for (var i = 0; i < files.length; i++) {  
                    fileData.append(files[i].name, files[i]);  
                }  
              
              
                console.log("comenzando carga");
                $.ajax({  
                    url: '/Acreditacion_Equipo/Acreditacion_Equipo_Carga',
                    type: "POST",  
                    contentType: false, 
                    processData: false,  
                    data: {id_query:id_query, fileData},
                   // data: fileData,id_query,
                    success: function (result) {  
                        alert(result);  
                    },  
                    error: function (err) {  
                        alert(err.statusText);  
                    }  
                });  
            } else {  
                alert("FormData no esta soportado");
                console.log("error no soportado");
            }  

y en mi controlador C# recibo bien el archivo pero el string id lo recibo null

 public ActionResult Acreditacion_Equipo_Carga(string id_query)
    {
        string id_ = id_query;
        // Checking no of files injected in Request object  
        if (Request.Files.Count > 0)
        {
            try
            {
                //  Get all files from Request object  
                HttpFileCollectionBase files = Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                    //string filename = Path.GetFileName(Request.Files[i].FileName);  

                    HttpPostedFileBase file = files[i];
                    string fname;

                    // Checking for Internet Explorer  
                    if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                    {
                        string[] testfiles = file.FileName.Split(new char[] { '\\' });
                        fname = testfiles[testfiles.Length - 1];
                    }
                    else
                    {
                        fname = file.FileName;
                    }

                    // Get the complete folder path and store the file inside it.  
                    fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                    file.SaveAs(fname);
                }
                // Returns message that successfully uploaded  
                return Json("File Uploaded Successfully!");
            }
            catch (Exception ex)
            {
                return Json("Error occurred. Error details: " + ex.Message);
            }
        }
        else
        {
            return Json("No files selected.");
        }
    }

No se porque esta pasando esto. alguna idea de como recibirlo ?

1 respuesta 1

2

Hay dos opciones para realizar lo que se está buscando.

La primera es: ya que se está enviando información desde un FormData y marcando la llamada ajax con un contentType = false. Lo que se necesita hacer es poner el id también el el FormData. En este caso algo así:

fileData.append('id_query', id);

Y hacer la llamada ajax solo con solo la variable FormData:

$.ajax({
    url: '/Acreditacion_Equipo/Acreditacion_Equipo_Carga',
    type: "POST",
    contentType: false,
    processData: false,
    data: fileData,
    success: function (result) {
        alert(result);
    },
    error: function (err) {
        alert(err.statusText);
    }
});

En el back end, leer ese valor con:

public ActionResult Acreditacion_Equipo_Carga()
{
    var tmp = Request.Form["id_query"];
    ...

La Segunda: es poner el id en el query string (y sugeriría se mandara como id, para aprovechar la tabla de ruteo de mvc):

$.ajax({
    url: '/Acreditacion_Equipo/Acreditacion_Equipo_Carga/'+  id_query,

Y en el controlador entonces si recibir el id

public ActionResult Acreditacion_Equipo_Carga(int id)
{ ...

ó seguir usando el id_query con:

$.ajax({
    url: '/Acreditacion_Equipo/Acreditacion_Equipo_Carga?id_query='+  id_query,

Y en el controlador

public ActionResult Acreditacion_Equipo_Carga(string id_query)
{ ...

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.