当前位置: 移动技术网 > IT编程>开发语言>.net > MVC中返回json数据的两种方式

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

2018年09月26日  | 移动技术网IT编程  | 我要评论

斗智天使路,lol琴瑟仙女的新春福袋,桑兰产子

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网