如何使用Ajax调用在MVC中的返回视图方法中返回JSON数据

时间:2014-12-15 15:58:39

标签: javascript jquery ajax asp.net-mvc json

我正在使用MVC和Ajax以及jQuery。我从我的动作方法返回我的JSON值,如下所示。

   public ActionResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
    {



        try
        {
            //ViewBag.InitParams = MvcApplication.objInitParams;
            string UserType = MvcApplication.objInitParams.UserType;


            bool Execute;
            List<MYSDR> MysdrListCollection = new List<MYSDR>();
            ServiceClient objService = new ServiceClient();
            objService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("v-saramb", "sdatnov@2014", "REDMOND");

            objService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            var result = String.Empty;

            if (RedirectView == "Agent View")
            {
                ViewData["Flag"] = "AgentView";
                #region Agent View                   
                result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
                #endregion
            }
            else if (RedirectView == "Manager View")
            {
                //result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");

                ViewData["Flag"] = "Manager View";
                userHUbdata.Clear();
                foreach (string Hub in UtilizationHubs)
                {
                    ServiceReference.MYSDRFields obj2 = new ServiceReference.MYSDRFields();
                    obj2.Hub = Hub;//cmbHubs.SelectedItem.ToString();
                    if (obj2.Hub != "All")
                        userHUbdata.Add(obj2);
                }


                result = objService.SalesDeskManagerView_ConditionbasedwithFilters("", "", userHUbdata, true);
            }
            //else  if (RedirectView == "BulkAssignment View")
            // {
            //     result = objService.SalesDeskManagerView("REDMOND\\v-susudh", "");
            // }


            XDocument xmldoc = null;
            try
            {
                xmldoc = XDocument.Parse(result.ToString());
                Execute = true;
            }
            catch
            {
                Execute = false;
            }
            if (Execute)
            {
                #region
                MysdrListCollection.Clear();


                var data = (from info in xmldoc.Elements("NewDataSet").Elements("Table1")
                            where Convert.ToString(info.Element("Status").Value) != "" && Convert.ToString(info.Element("Status").Value) != "New" && Convert.ToString(info.Element("Status").Value) != "Projected"
                            select new MYSDR
                            {
                                SRNO = Convert.ToString(info.Element("SRNO").Value),
                                CustomerName = Convert.ToString(info.Element("CustomerName0").Value),
                                ServiceLevel = Convert.ToString(info.Element("TypeofRequest").Value.Replace("Unsolicited", "Proactive").Replace("Partner Proactive", "Proactive")),
                                CRMID = Convert.ToString(info.Element("CRMID").Value),
                                //DueDate_Date = Convert.ToDateTime(info.Element("DueDate").Value),
                                RequestType = ((Convert.ToString(info.Element("TypeofRequest").Value) == "Managed Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Standard Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal Lite")) ? "Proposal" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "AIO") || (Convert.ToString(info.Element("TypeofRequest").Value) == "AIO Prep")) ? "AIO" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Full") || (Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Light")) ? "M&A" : Convert.ToString(info.Element("TypeofRequest").Value),
                                Region = Convert.ToString(info.Element("Region").Value),
                                Segment = Convert.ToString(info.Element("Segment").Value),
                                Assigned = ((Convert.ToString(info.Element("Status").Value) == "Projected") || ((Convert.ToString(info.Element("Status").Value) == "New"))) ? "Assign" : Convert.ToString(info.Element("AssignedToName").Value),
                                Language = Convert.ToString(info.Element("Language").Value),
                                ID = Convert.ToString(info.Element("ID").Value),
                                Status = Convert.ToString(info.Element("Status").Value),
                                AM = Convert.ToString(info.Element("AM").Value),
                                Hub = Convert.ToString(info.Element("Hub").Value),
                                DueDate = Convert.ToDateTime(info.Element("DueDate").Value).Date,
                                RequestDate = Convert.ToDateTime(info.Element("Requestdate").Value).Date,
                                PrimaryContact = Convert.ToString(info.Element("PrimaryContact").Value),
                                Country = Convert.ToString(info.Element("Country").Value),
                                SolutionForProposal = Convert.ToString(info.Element("SolutionForProposal").Value),
                                Reactive = ((Convert.ToString(info.Element("TypeofRequest").Value).Contains("Research")) && (Convert.ToString(info.Element("RequestOrigin").Value) == "Reactive")) ? "R" : "",
                                CoOwner = ((Convert.ToString(info.Element("Status").Value) == "New") || (Convert.ToString(info.Element("Status").Value) == "Projected") || (Convert.ToString(info.Element("TypeofRequest").Value).StartsWith("QA"))) ? "" : (((Convert.ToString(info.Element("Status").Value) != "New") || (Convert.ToString(info.Element("Status").Value) != "Projected")) && (Convert.ToString(info.Element("Coowner").Value) == "")) ? "Add Co-Owner" : (Convert.ToString(info.Element("Coowner").Value)),

                            }).AsEnumerable();
                MysdrListCollection = data.ToList<MYSDR>();
                // Session["MYSDRGridAgentView"] = MysdrListCollection.OrderBy(a => a.DueDate);
                // return View(data);
                #endregion

            }

            var serializer = new JavaScriptSerializer();
            var resultContent = new ContentResult();
            serializer.MaxJsonLength = Int32.MaxValue; // Whatever max length you want here
            resultContent.Content = serializer.Serialize(MysdrListCollection.OrderBy(a => a.DueDate));
            resultContent.ContentType = "application/json";
            return resultContent;
            // return Json(MysdrListCollection.OrderBy(a => a.DueDate),JsonRequestBehavior.AllowGet);
            // return View("Mysdrviews",MysdrListCollection.OrderBy(a => a.DueDate));
            //return MysdrListCollection; 



        }




        catch (Exception ex)
        {
            return Json("");
        }





    }

我正在使用jQuery中的Ajax调用,如下所示。

 $.ajax({
        url: '@Url.Action("GetMYSDRViews", "MYSDR")',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        // url: '/MYSDR/PostbtnSubmit',
        data: JSON.stringify({ AssetNames: itemsListAssets, UtilizationHubs: itemUtilizationHub, RedirectView: 'Manager View' }),

        success: function (result) {
             debugger;
            var grid = $('#MYSDRGridAgentView').getKendoGrid();
            grid.dataSource.data(result);
            grid.refresh();
            $('#Loader').oLoader('hide');
            // $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {
             debugger;
            // $('#result').html(response);
        }
    });

到这里一切都很好。但是当我尝试在我的返回视图方法中返回我的JSON结果时,我没有收到任何错误,但是我无法成功返回结果,而且我的调试器品脱也没有达到成功错误函数。

请告诉我在哪里更改我的Ajax功能。我被困在这里。

1 个答案:

答案 0 :(得分:0)

使函数成为JsonResult并返回Json(某事)。

public JsonResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
   ...
   return Json(MysdrListCollection.OrderBy(a => a.DueDate));

}

你把失败而不是错误。

   error: function (response) {
         debugger;
        // $('#result').html(response);
    }