Two ways to return json data in MVC

In MVC, if the data is directly returned to the front-end page, we usually use return view();

So I don't want to use razor syntax directly. After all, razor is too hard to remember. It's not as comfortable as writing ajax docking

So we can do that

1. Define ActionResult and return json. The tag attribute can be HttpPost or HttpGet according to your own needs

 public ActionResult UpdateDownloadInJson(string deviceNames,string programNames)
        {
            string[] deviceName = deviceNames.Split(',');
            string[] programName = programNames.Split(',');
            List<DownloadViewModel> DownloadViewModelList = new List<DownloadViewModel>();
            foreach (string tempDeviceName in deviceName)
            {
                var _deviceId=deviceInfoService.FindSingle<DeviceInfo>(r => r.DeviceName == tempDeviceName).Id;
                foreach (string tempProgramName in programName)
                {
                    int _programId = publishDetailService.Set<ProgramInfo>().Where(r => r.ProgramName == tempProgramName).FirstOrDefault().Id;
                    var progress= publishDetailService.Set<DeviceMaterial>().Where(r => r.DeviceId == _deviceId && r.ProgramId == _programId).FirstOrDefault().DownProgress;
                    DownloadViewModelList.Add(new DownloadViewModel
                    {
                        DeviceId= (int)_deviceId,
                        DeviceName = tempDeviceName,
                        ProgramName = tempProgramName,
                        DownloadProgress = (int)progress
                    });
                }
            }
            return Json(new AjaxResult
            {
                Result = DoResult.Success,
                RetValue = DownloadViewModelList
            }, JsonRequestBehavior.AllowGet);
        }

2. Use JsonResult to process ajax requests

[HttpPost]
        [HandlerAjaxOnly]
        public JsonResult CheckLogin(string username, string password, string code)
        {
            UserManage.LoginResult result = this.HttpContext.UserLogin(username, password, code);
            if (result == UserManage.LoginResult.Success)
            {
                return Json(new AjaxResult { Result = DoResult.Success, DubugMessage = "Login succeeded." });
            }
            else
            {
                return Json(new AjaxResult { Result = DoResult.Faild, DubugMessage = "Login failed," + result.ToString() });
            }
        }

The specific difference will be added later, and the usage is basically like this.

Tags: ASP.NET JSON Attribute

Posted on Wed, 25 Dec 2019 13:33:08 -0500 by gregmiller