locked
Helpe Me !!! RRS feed

  • Question

  • User1692641958 posted

    Hi, I have a problem, I have created a method that returns a list of a procedure, I convert it into a json, and I consume it in an ajax with a method with 2 parameters, but when I call that method in js I get an error

    public static previewFlashReport getTraResDesMed(int COMD_ID,string COMD_ESTABLECIMIENTO)
    {
    previewFlashReport _previewFlashReport= null;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexion"].ToString());
    SqlCommand cmd = new SqlCommand();
    try
    {
    cmd.Connection = con;
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.CommandText = "dbo.DesTra";
    cmd.Parameters.AddWithValue("@ID", COMD_ID);
    cmd.Parameters.AddWithValue("@EST", COMD_ESTABLECIMIENTO);
    con.Open();
    SqlDataReader rdr;
    rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
    _previewFlashReport = new previewFlashReport();
    _previewFlashReport.DesMed = rdr["DesMed"].ToString();
    _previewFlashReport.TraRes = rdr["TraRes"].ToString();

    }
    return _previewFlashReport;
    }
    catch (Exception ex)
    {
    Logger.error("Error en el metodo", ex);
    return _previewFlashReport;
    }
    finally
    {
    con.Close();
    }


    }

    public JsonResult obtenerTraResDesMed(int iCodigoAtencion, String COMD_ESTABLECIMIENTO)
    {
    return Json(ConsultaDAL.getTraResDesMed(iCodigoAtencion, COMD_ESTABLECIMIENTO));
    }

    function ListadoTraResDesMedPorIdesta(iCodigoAtencion, COMD_ESTABLECIMIENTO) {
    $.ajax({
    type: 'POST',
    url: '/Consulta/obtenerTraResDesMed',
    dataType: 'json',
    data: {
    iCodigoAtencion: iCodigoAtencion,
    COMD_ESTABLECIMIENTO: COMD_ESTABLECIMIENTO
    },
    success: function (data) {

    return {
    DesMed : data.DesMed,
    TraRes : data.TraRes
    }

    },
    error: function (ex) {
    alert('Error al buscar TraResDesMed.' + ex.toString());
    }
    });

    }

    const iCodigoAtencion= JSON.parse(parametros).iCodigoAtencion;
    const COMD_ESTABLECIMIENTO = JSON.parse(parametros).COMD_ESTABLECIMIENTO;
    const lis= listado.ListadoTraResDesMedPorIdesta(iCodigoAtencion
    , COMD_ESTABLECIMIENTO);

    Wednesday, August 29, 2018 6:01 PM

All replies

  • User475983607 posted

    Please stop posting "Help Me" in the subject.  Use a descriptive subject that describes the issue.  

    I have created a method that returns a list of a procedure, I convert it into a json, and I consume it in an ajax with a method with 2 parameters, but when I call that method in js I get an error

    Is there any way you can post the actual error? 

    Also it's not clear how parametros is populated.  Can you explain the design?

    const iCodigoAtencion= JSON.parse(parametros).iCodigoAtencion;
    const COMD_ESTABLECIMIENTO = JSON.parse(parametros).COMD_ESTABLECIMIENTO;
    

    Try pressing F12 to open developer tools and look for errors in the console.

    Wednesday, August 29, 2018 6:29 PM
  • User753101303 posted

    Hi,

    I get an error

    Always tell which error you have (and never start a debug session by reading your code, you should first look at what happens when your code runs, you can then focus on the part of your code where the problem happens).

    See http://api.jquery.com/jQuery.ajax/

    For now it seems a misunderstanding about how Ajax is working. It is asynchronous ie the htp query is triggered and then the next statemenr immediately runs... Callbacks are called later once the http request is completed. The doc shows how to deal with that using "callbacks" or "promises" which allow to chain more easily multiple callbacks.

    For now I suggest to move all the logic you need in the success callback so that you can quickly get how it works.

    Wednesday, August 29, 2018 6:42 PM
  • User-893317190 posted

    Hi RockChris,

    It seems that you want a list of procedures instead of a single row of data. I suggest you modify your method getTraResDesMed to return  a list of data.

    I find your try to return the result of ajax in the ajax's success callback. It won't work.

    Below is my code.

    Code in controller.

      public JsonResult Index(int id)
            {
                return Json(getTraResDesMed(id),JsonRequestBehavior.AllowGet);
            }
    
            public class Entry
            {
               
                public string  Code { get; set; }
                public string  Description { get; set; }
            }
            public static List<Entry> getTraResDesMed(int id)
            {
    //declare a list to store a list of data
                List<Entry> list = new List<Entry>();
                SqlConnection  con = new SqlConnection(ConfigurationManager.ConnectionStrings["EntityExe"].ToString());
                SqlCommand cmd = new SqlCommand();
                try
                {
                    cmd.Connection = con;
                   
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "entity_pro";
                    cmd.Parameters.AddWithValue("@ID", id);
             
                    con.Open();
                    SqlDataReader rdr;
                    rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
    // declare a model 
                        Entry entry = new Entry();
                        entry.Code = rdr["Code"].ToString();
                     entry.Description = rdr["Description"].ToString();
    // add the current model to the list
                        list.Add(entry);
                    }
                    return list;
                }
                catch (Exception ex)
                {
                 
                    return list;
                }
                finally
                {
                    con.Close();
                }
    
            }

    Html page. Normally , we directly manipulate the data returned by the  success callback instead of return it.

     $.ajax({
                    type: 'POST',
                    url: '/Data/index',
                    dataType: 'json',
                    data: {
                       id: 3,
                       
                    },
                    success: function (data) {
    
                        console.log(data);
    
                    },
                    error: function (ex) {
                        alert('Error al buscar TraResDesMed.' + ex.toString());
                    }
                });

    If you must use a function with an ajax call in it.you could use code below. However,it is not recommended , because it will make the method not asynchronous.

      function ListadoTraResDesMedPorIdesta(id) {
                //declare a variable to receive the data returned by ajax
                var myData = null;
                $.ajax({
                    type: 'POST',
                   async:false,
                    url: '/Data/index',
                    dataType: 'json',
                    data: {
                      id:id
                    
                    },
                    success: function (data) {
    
                        myData = data;
    
                    },
                    error: function (ex) {
                        alert('Error al buscar TraResDesMed.' + ex.toString());
                    }
                });
                return myData
            }
            var list = ListadoTraResDesMedPorIdesta(3);
            console.log(list);

    Best regards,

    Ackerly Xu

    Thursday, August 30, 2018 7:25 AM