简体   繁体   English

不通过C#控制器操作返回AJAX成功

[英]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 ? 无法从C#控制器操作返回到AJAX成功我尝试了许多可用的选项,但是它仍然没有将数据返回给AJAX成功,这可能是什么原因? 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 我想将列表Listemr_t_Immunization从控制器的操作返回给我的AJAX调用的成功数据,我该怎么做

Please See The Following Code Thank You 请看下面的代码谢谢

AJAX Request AJAX请求

$.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); 我已经使用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'. 使用类型'System.Data.Entity.DynamicProxies.as_t_appointment_305685F58BEE75BAC95975F9457412A0DE58BB59D3EDBD1155C7DB5E21A7BA66'检测到自引用循环。 Path '[0].erx_t_patient.as_t_appointment[0].erx_t_city.as_t_appointment' 路径'[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. 乍一看,除非您的条件之一失败,否则您似乎可以将失败的返回值移动到else语句中,以防止它们被解雇,而不仅仅是自己漂浮在外面。

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. 另外,处理API类内容的成功和失败的更好方法是使用HTTP错误代码。

 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: 我猜这是db是您的上下文对象,如果是这样,请替换为:

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. 我不是100%知道erx是什么,但是如果您检查是否有结果,则将其更改为。

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

    }

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

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