MVC裡面如果直接將數據返回到前端頁面,我們常用的方式就是用return view(); 那麼我不想直接用razor語法,畢竟razor這玩意兒實在是太難記了,還不如寫ajax對接來得舒服不是 那麼我們可以這麼做 1.定義ActionResult,返回json,標記屬性可以採用HttpPost,也可 ...
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() }); } }
具體的區別後續補充,用法基本就是這樣。