将 JSON 对象传递到服务器端并解析函数

代码的整体意图提供的代码是通过angularJS从登录页面获取用户名和密码。它被传递给包含 AJAX 脚本的函数。然后,数据被传递到服务器端,并应与数据库中的数据进行比较。如果一切顺利,它应该将会话ID和用户名推送到会话以进行身份验证和授权。


提供的脚本的用途:我正在尝试将JSON对象传递到服务器端。我已经关闭了JSON,但是在函数中检索它并从对象中获取值是我丢失的地方。


我以前尝试过什么:我尝试过使用列表类和字符串。我将显示列表以及我卡住的位置和字符串。


AJAX:


    login: function (username, password) {

                var cred = { "uname": username, "pass": password };

                var response = $http({

                    method: "post",

                    url: "/Login/CheckUser",

                    data: JSON.stringify({ model: cred }),

                    contentType: 'application/json; charset=utf-8',

                    dataType: "JSON",

                    success: function (msg) {

                        if (msg) {

                            console.log("success");

                        }

                    },

                    error: function (msg) {

                        if (msg) {

                            console.log("fail");

                        }

                    }

使用字符串方法:


   [HttpPost]

        public string CheckUser(String umodel) 

        {

            Console.Write(umodel);

            string modelCheck = umodel;

/*not sure how to parse from here */

列表:


        public class userCred

        {

            public string uname { get; set; }


            public string pass { get; set; }



            public List<userCred> userCreds = new List<userCred>();


        }

   

预期结果将是成功将 JSON 对象传递到服务器端以比较数据库中的数据,并根据它们是否匹配返回 0 或新会话。


隔江千里
浏览 78回答 1
1回答

心有法竹

对于你的 JavaScript 有效负载对象,创建一个确切的模型,比如 UserCredpublic class UserCred{&nbsp; &nbsp; public string Uname { get; set; }&nbsp; &nbsp; public string Pass { get; set; }}现在,当您执行 AJAX 帖子时,MVC 会将有效负载绑定到模型。要访问您的属性,只需使用 model.property[HttpPost]public string CheckUser(UserCred model)&nbsp;{&nbsp; if(!ModelState.IsValid)&nbsp; {&nbsp; &nbsp; return "0";&nbsp; }&nbsp; &nbsp; string uname = model.Uname;&nbsp; &nbsp; string pword = model.Pass;&nbsp; &nbsp; /* Your Code&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;*/&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP