MVC中返回json數據的兩種方式


首先解釋一下ActionResultIActionResult

ActionResult一般用來返回ViewResult,PartialViewResult,JsonResult

IActionResult一般用來返回預定義響應和錯誤,比如404

MVC里面如果直接將數據返回到前端頁面,我們常用的方式就是用return view();

那么我不想直接用razor語法,畢竟razor這玩意兒實在是太難記了,還不如寫ajax對接來得舒服不是

那么我們可以這么做

1.定義ActionResult,返回json,標記屬性可以采用HttpPost,也可以是用HttpGet,按自己的需求來使用

 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.采用JsonResult,最主要拿來處理ajax請求

[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 = "登陸成功。" });
            }
            else
            {
                return Json(new AjaxResult { Result = DoResult.Faild, DubugMessage = "登陸失敗," + result.ToString() });
            }
        }

具體的區別后續補充,用法基本就是這樣。

PS:

補充部分:

IActionResult的具體使用

在具體定義時,可以看到,返回的結果是不一樣的,這里可以返回預定義的響應,及一些錯誤

 public IActionResult Update(string id, Movie imovie)
        {
            var imovie = _movieService.Get(id);
            if (imovie== null)
            {
                return NotFound();
            }
            _movieService.Update(id, imovie);
            return NoContent();
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM