Home > Vue.Js > how to insert and retrieve data from Database in Vue js



how to insert and retrieve data from Database in Vue js

In this article, we have described how to insert and retrieve data from the database in Vue js with example code.


In this article,we have described how to insert and retrieve data from database in vue js with example code.

vue js start from create a vue js instance and element id and data.

 

Required Namespaces:

We must use the following namespaces.

using System.Data;

using Newtonsoft.Json;

using System.Configuration;

using System.Data.SqlClient;

using System.Web.Services;

Script

<script>

    var app = new Vue({

        el: '#app',

        data: {

            UsersData: [],

            Name: '',

            role: ''

        },

        methods: {

            OnSubmit: function () {

                var ObjectD = { "name": this.Name, "role": this.role };

                $.ajax({

                    type: "POST",

                    url: "MasterPage.aspx/NewUsers",

                    data: JSON.stringify({ "user": ObjectD }),

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

                    dataType: "json",

                    success: function (data) {

                    }

                });

            }

        },

        created: function () {

            let cobject = this; // here stored currect instance

            var ObjectD = { "name": this.Name, "role": this.role };

            $.ajax({

                type: "POST",

                url: "MasterPage.aspx/GetData",

                data: JSON.stringify({ "user": ObjectD }),

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

                dataType: "json",

                success: function (data) {

                    cobject.UsersData = JSON.parse(data.d);

                }

            });

        }

    })

</script>

I have provided sample code below. You can have a look at it and learn about code.

The most basic form of data insert and retrive in table and list of items using double curly braces.

vue.js is a progressive framework for building user interfaces which are used for two way bind.

Vue.js is a lightweight alternative to other Javascript frameworks like AngularJS.

 

Html

<html>

<head runat="server">

    <title></title>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <div id="app">

                <div class="form-group row">

                    <div class="col-xs-2">

                        <label for="ex2">Name</label>

                        <input class="form-control" v-model="Name" id="txtUserName" type="text">

                    </div>

                    <div class="col-xs-4">

                        <label for="ex2">Role</label>

                        <select class="form-control" v-model="role" id="ddlRole">

                            <option selected="selected" value="0">Select</option>

                            <option value="1">Admin</option>

                            <option value="2">vice-Admin</option>

                            <option value="3">Member</option>

                        </select>

                    </div>

                    <div class="col-xs-4">

                        <label for="ex2"></label>

                        <button type="button" v-on:click="OnSubmit" id="btnSubmit">

                            Submit</button>

                    </div>

                </div>

                <br />

                <br />

                <table class="table table-bordered">

                    <thead>

                        <tr>

                            <th>Id</th>

                            <th>Name</th>

                            <th>role</th>

                        </tr>

                    </thead>

                    <tbody>

                        <tr v-for="users in UsersData">

                            <td>{{users.id }}</td>

                            <td>{{users.Name }}</td>

                            <td>{{users.role }}</td>

                        </tr>

                    </tbody>

                </table>

            </div>

        </div>

    </form>

</body>

</html>

C#

We have explained below C# code and added the examples of some user information in this article .You can have a look at it and learn.

[WebMethod]

public static string NewUsers(Users user)

{

string config = Convert.ToString(ConfigurationManager.ConnectionStrings["myconnection"]);

List<Users> Users = new List<Users>();

SqlConnection con = new SqlConnection(config);

con.Open();

using (SqlCommand cmd = new SqlCommand("insert into users values(@Name,@Role)", con))

{

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = user.Name;

cmd.Parameters.Add("@Role", SqlDbType.VarChar).Value = user.role;

cmd.ExecuteNonQuery();

}

con.Close();

return JsonConvert.SerializeObject(new { status = true, });

}

/// <summary>

/// this function get all users data.

/// </summary>

/// <returns></returns>

[WebMethod]

public static string getData()

{

string config = Convert.ToString(ConfigurationManager.ConnectionStrings["myconnection"]);

List<Users> Users = new List<Users>();

SqlConnection con = new SqlConnection(config);

con.Open();

using (SqlCommand cmd = new SqlCommand("Select * from Users", con))

{

SqlDataReader idr = cmd.ExecuteReader();

if (idr.HasRows)

{

Users = populateLisst(idr, con);

}

}

con.Close();

return JsonConvert.SerializeObject(Users);

}

public static List<Users> populateLisst(SqlDataReader idr, SqlConnection con)

{

List<Users> usersI = new List<Users>();

while (idr.Read())

{

usersI.Add(new Users

{

id = Convert.ToInt32(idr["userId"]),

Name = Convert.ToString(idr["name"]),

role = Convert.ToString(idr["role"])

});

}

return usersI;

}

public class Users

{

public int id { getset; }

public string Name { getset; }

public string role { getset; }

}

 




Note: All contents are copyright of their authors.



Comments



Leave a Reply

Comment:*
Email ID:*


Name:*