分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

MVC中返回json数据的两种方式

发布时间:2023-09-06 02:16责任编辑:林大明关键词:jsjsonMVC

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() }); ???????????} ???????}

具体的区别后续补充,用法基本就是这样。

MVC中返回json数据的两种方式

原文地址:https://www.cnblogs.com/yinxuejunfeng/p/9685460.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved