Search code examples
c#jsonasp.net-mvc-5server-side

Passing JSON object to Server side and parsing in function


The overall intention of the code The code provided is taking a username and password from a login page via angularJS. It is passed to the function which houses the AJAX script. The data is then passed server side and should be compared against data in the database. If all goes well, it should push a session ID and username to the session for authentication and authorization purposes.

Purpose of the script provided: I am attempting to pass the JSON object to the server side. I have the JSON down, but retrieving it in the function and getting the values from the object is where I am lost.

What have I tried previously: I have tried using a list class and a string. I will show the list and where I got stuck and the string.

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

using the string method:

   [HttpPost]
        public string CheckUser(String umodel) 
        {
            Console.Write(umodel);
            string modelCheck = umodel;
/*not sure how to parse from here */

List:

        public class userCred
        {
            public string uname { get; set; }

            public string pass { get; set; }


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

        }
        [HttpPost]
        public string CheckUser(List<userCred> umodel) 
        {


            string uname = "";
            string pword = "";

/*Not sure how to access values from JSON here */

            /*  Begin Assigning values 
             *  Validation check
             */
            using (localtestEntities entity = new localtestEntities())
            {
                var user = entity.users.Where(u => u.uname == uname).FirstOrDefault();
                if (user != null)
                {
                    if (pword == user.pw)
                    {
                        Session["LoginID"] = user.id;
                        Session["Username"] = user.fname + ' ' + user.lname;
                        return user.id.ToString();
                    }
                    else
                    {
                        return "0";
                    }
                }
                else
                {
                    return "0";
                }
            }
            /* Begin Assigning values */
        } //End Check User

Expected result would be successfully passing a JSON object to the serverside for comparison of data within the database and return 0 or new session depending on if they match or not.


Solution

  • For your JavaScript payload object, create an exact model say UserCred

    public class UserCred
    {
        public string Uname { get; set; }
        public string Pass { get; set; }
    }
    

    Now when you do an AJAX post, MVC will bind your payload to the model. And to access your properties just use model.property

    [HttpPost]
    public string CheckUser(UserCred model) 
    {
      if(!ModelState.IsValid)
      {
        return "0";
      }
        string uname = model.Uname;
        string pword = model.Pass;
    
        /* Your Code
         *  
         */
    
     }