MVC中返回json数据的两种方式
程序员文章站
2024-02-27 12:02:09
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() }); } }
具体的区别后续补充,用法基本就是这样。