简体   繁体   中英

Not Returning To AJAX Success From C# Controller Action

Not Returning To AJAX Success From C# Controller Action I Have Tried Many Options Available But Its Still Not Returning Data To AJAX Success What Could Be The Reason ? I Want To Return List Listemr_t_Immunization From Action Of Controller To My Success data Of The AJAX Call How Should I Do That

Please See The Following Code Thank You

AJAX Request

$.ajax(
             {
                 url: '@Url.Action("getmedi", "Immunization")',
                 type: 'Post',
                 async: false,
                 contentType: 'application/json',
                 dataType: "json",
                 data: JSON.stringify({ "patient2": patient2}),
                 success: function (data) {
                     debugger
                     $(data).each(function(index, element){
                         $('#first > tbody').append('<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
                         $('#first > tbody > tr:last-child > td:nth-child(1)').append('<input id='+element.ImmunizationId+' value='+element.VaccineName+'>');
                         $('#first > tbody > tr:last-child > td:nth-child(2)').append('<input id='+element.Immunization_Id+' value='+element.DateGiven+'>');
                         $('#first > tbody > tr:last-child > td:nth-child(3)').append('<input id='+element.Immunization_Id+' value='+element.Route+'>');



                     })
                     $("input[name='VaccineName']").attr('disabled', 'disabled');
                     $("input[name='DateGiven']").attr('disabled', 'disabled');
                     $("input[name='Route']").attr('disabled', 'disabled');

                 },
                 error: function (textStatus, errorThrown)
                 {
                     debugger
                 }

             });

Controller Action

[HttpPost]
public JsonResult getmedi(int patient2)
        {
            if (patient2.ToString() != "")
            {
                string roster = objOrgCont.getmedi(patient2);

                JavaScriptSerializer ser = new JavaScriptSerializer();

                emr_t_Immunization erx = (emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));

                List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();

                ///List<emr_t_Medical_History> Listemr_t_Medical_History2 = (from Allemr_t_Medical_History in db.emr_t_Medical_History where Allemr_t_Medical_History.Mr_No == Mr_No select Allemr_t_Medical_History).ToList();

                if (erx != null)
                {
                    //return Json(new { success = true, for_Date = erx.Med_Date, for_Name = erx.Name, for_Active = erx.Active, for_Resolved = erx.Resolved, for_Comments=erx.Comments });
                    return Json(new { Listemr_t_Immunization, JsonRequestBehavior.DenyGet });
                }

            }

            return Json(new { success = false });

        }

I Have Also Tried To Stringify It Before Returning And It Shows Following Error

I Have Used return JsonConvert.SerializeObject(Listemr_t_Immunization);

Now It Is Giving Me Error

Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.as_t_appointment_305685F58BEE75BAC95975F9457412A0DE58BB59D3EDBD1155C7DB5E21A7BA66'. Path '[0].erx_t_patient.as_t_appointment[0].erx_t_city.as_t_appointment'

Just from a quick glance, it looks like you could move your failure returns into else statements to protect them from being fired unless one of your conditions fail, rather than just floating outside on its own.

Is the issue that your call back fails every time? If so that could be the reason.

[HttpPost]
public JsonResult getmedi(int patient2)
    {
        if (patient2.ToString() != "")
        {
            string roster = objOrgCont.getmedi(patient2);

            JavaScriptSerializer ser = new JavaScriptSerializer();

            emr_t_Immunization erx = (emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));

            List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();

            ///List<emr_t_Medical_History> Listemr_t_Medical_History2 = (from Allemr_t_Medical_History in db.emr_t_Medical_History where Allemr_t_Medical_History.Mr_No == Mr_No select Allemr_t_Medical_History).ToList();

            if (erx != null)
            {
                //return Json(new { success = true, for_Date = erx.Med_Date, for_Name = erx.Name, for_Active = erx.Active, for_Resolved = erx.Resolved, for_Comments=erx.Comments });
                return Json(new { Listemr_t_Immunization, JsonRequestBehavior.DenyGet });
            } else 
            {
               return Json(new { success = false });
            }
        } else

        {
          return Json(new { success = false });
        }

    }

Also on a side note, a better way to deal with success and failure of API-ish stuff is to use the HTTP error codes.

 Response.StatusCode = (int)HttpStatusCode.Created;
 return Json(new { results });

EDIT

To send a list back in your request.

This line here will need to change:

List<emr_t_Immunization> Listemr_t_Immunization = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList();

I am guessing that db is your context object and if so replace that line with:

var results = db.emr_t_Immunization.Where(Allemr_t_Immunization => Allemr_t_Immunization.Patient_Id == patient2).ToList()

I am not 100% sure what erx is, but if you are checking that you have results then change that to.

  if (results.Any())
    {
     Response.StatusCode = (int) HttpStatusCode.Created;
     return Json(new { results });
    } else 
    {
      Response.StatusCode = (int)HttpStatusCode.BadRequest;
      return Json("Failed");
    }

So all up your code will read:

 [HttpPost]
     public JsonResult getmedi(int patient2)
      {
          if (patient2.ToString() != "")
          {
            string roster = objOrgCont.getmedi(patient2);
            JavaScriptSerializer ser = new JavaScriptSerializer();
            emr_t_Immunization erx =(emr_t_Immunization)ser.Deserialize(roster, typeof(emr_t_Immunization));
            var results = db.emr_t_Immunization.Where(Allemr_t_Immunization     => Allemr_t_Immunization.Patient_Id == patient2).ToList()
            /// You can make that query easier to read by having
            /// var results = db.emr_t_Immunization.Where(a => a.Patient_Id == patient2).ToList()
        if (results.Any())
         {
          Response.StatusCode = (int) HttpStatusCode.Created;
          return Json(new { results });
         } else 
         {
           Response.StatusCode = (int)HttpStatusCode.BadRequest;
           return Json("Failed");
         }
      } else
      {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json("Failed");
      }

    }

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