IMG-LOGO

Vue JSON example and form input binding

andy - 18 Dec, 2017 16168 Views 1 Comment

In this tutorial, you will learn how to retrieve a JSON data using C# Web API and populate the JSON data content into the form inputs using Vue. For this example, I will create a guestbook database table which will contain a FirstName, LastName and Email Address. I will use SQL Server to create this demo table.


CREATE TABLE [dbo].[Guest_Book](
	[GuestID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](50) NOT NULL,
	[LastName] [nvarchar](50) NOT NULL,
	[Email] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Guest_Book] PRIMARY KEY CLUSTERED 
(
	[GuestID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


-- INSERT Sample Data
INSERT INTO Guest_Book VALUES ('Jacob', 'Anderson', 'jacoband@example.com');
GO

INSERT INTO Guest_Book VALUES ('Ben', 'Thomson', 'benthom@example.com');
GO

We will create two stored procedures which will perform getting the customer information and update the customer information from the form inputs. Here are the two stored procedures.

-- Stored procedure to get guest book information
CREATE PROCEDURE GetGuestBook
	-- Add the parameters for the stored procedure here
	@GuestID numeric(18,0)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM Guest_Book
	WHERE GuestID = @GuestID
END
GO


-- stored procedure to update the guest book information
CREATE PROCEDURE UpdateGuestBook
	-- Add the parameters for the stored procedure here
	@GuestID numeric(18,0),
	@Firstname nvarchar(50),
	@LastName nvarchar(50),
	@Email nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	UPDATE Guest_Book
	SET FirstName = @Firstname,
		LastName  = @LastName,
		Email	  = @Email
	WHERE GuestID = @GuestID
END
GO

The next part is to create the C# Entity Class for the GuestBookInfo, Data Access Layer to Get and Update guest book information and the Web API interface handler to accept JSON Post data. Here is the code for the C# Entity class GuestBookInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByTutorialVueExample.Entities
{
    public class GuestBookInfo
    {
        public long GuestID { get; set; }
        public string FirstName { get; set;}
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

This will be the code for data access layer accessing the stored procedure of database.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ByTutorialVueExample.Entities;

namespace ByTutorialVueExample.Handlers {
    public static class GuestBookHandler {
		private string _connectionString = "Enter connection string here.";
        public static GuestBookInfo GetGuestBook(long guestID) {
            GuestBookInfo objGuestBook = new GuestBookInfo();
            using (SqlConnection objConnection = new SqlConnection(_connectionString)) {
                SqlCommand objCommand = new SqlCommand("GetGuestBook", objConnection);
                objCommand.CommandType = CommandType.StoredProcedure;
                objCommand.Parameters.Add(new SqlParameter("@GuestID", guestID));
                objConnection.Open();
                SqlDataReader objReader = objCommand.ExecuteReader();
                if (objReader.Read()) {
                    objGuestBook.GuestID = long.Parse(objReader["GuestID"].ToString());
                    objGuestBook.FirstName = objReader["FirstName"].ToString();
                    objGuestBook.LastName = objReader["LastName"].ToString();
                    objGuestBook.Email = objReader["Email"].ToString();
                }
                objReader.Close();
                objReader.Dispose();
                objConnection.Close();
                objConnection.Dispose();
                objCommand.Dispose();
            }
            return objGuestBook;
        }
		
        public static void UpdateGuestBook(GuestBookInfo objGuestBook)
        {
            using (SqlConnection objConnection = new SqlConnection(_connectionString))
            {
                SqlCommand objCommand = new SqlCommand("UpdateGuestBook", objConnection);
                objCommand.CommandType = CommandType.StoredProcedure;
                objCommand.Parameters.Add(new SqlParameter("@GuestID", objGuestBook.GuestID));
                objCommand.Parameters.Add(new SqlParameter("@FirstName", objGuestBook.FirstName));
                objCommand.Parameters.Add(new SqlParameter("@LastName", objGuestBook.LastName));
                objCommand.Parameters.Add(new SqlParameter("@Email", objGuestBook.Email));
                objConnection.Open();
                objCommand.ExecuteNonQuery();
                objConnection.Close();
                objConnection.Dispose();
                objCommand.Dispose();
            }
        }

    }
}

This will be the Web API handler code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using ByTutorialVueExample.Entities;
using ByTutorialVueExample.Handlers;

namespace ByTutorialVueExample.WebAPI
{
    public class GuestBookController : ApiController {
		
		[HttpPost]
        public HttpResponseMessage GetGuestBook([FromBody]GuestBookInfo objGuestBook) {
            GuestBookInfo returnGuestBook = GuestBookHandler.GetGuestBook(objGuestBook.GuestID);
            return Request.CreateResponse(HttpStatusCode.OK, returnGuestBook);
        }
		
        [HttpPost]
        public HttpResponseMessage UpdateGuestBook([FromBody]GuestBookInfo objGuestBook) {
            GuestBookHandler.UpdateGuestBook(objGuestBook);
            return Request.CreateResponse(HttpStatusCode.OK, "");
        }
	}
}

Once our server code is done, we can now focus on our front end code. This will be the full code of our front end html file. I will include further explanation on the next couple paragraphs.

<!DOCTYPE HTML>
<html>
<head>
	<script src="https://cdn.jsdelivr.net/npm/Vue"></script>
	<style>
		.label{
			font-weight:bold;
			margin-bottom:5px;
		}
		
		.form-input{
			margin-bottom:10px;
		}
	</style>
</head>
<body>
<div id="guestbook-app">
	<div class="label">First Name</div>
	<div class="form-input"><input type="text" v-model="guestBook.FirstName"/></div>
	<div class="label">Last Name</div>
	<div class="form-input"><input type="text" v-model="guestBook.LastName"/></div>
	<div class="label">Email</div>
	<div class="form-input"><input type="text" v-model="guestBook.Email"/></div>
	<div class="form-input"><button type="button" v-on:click="updateGuestBook">Update</button></div>
	<div><input type="hidden" v-model="guestBook.GuestID"/></div>
</div>
<script>
var app = new Vue({
  el: '#guestbook-app',
  data: {
	guestBook: []
  },
  methods: {
	getGuestBook: function(){
		var self = this;
		
		//we pass an example guest ID Key equals to 1
		var jsonData = {
			GuestID: 1
		}
		fetch("https://bytutorial.com/API/GuestBook/GetGuestBook", {
			method: 'post',
			headers: {'Content-Type':'application/json; charset=utf-8'},
			body: JSON.stringify(jsonData)
		}).then(function(response) {
			return response.json();
		}).then(function(return_data){
			self.guestBook = return_data;
		});
	},
	
	updateGuestBook: function(){
		var self = this;
		fetch("https://bytutorial.com/API/GuestBook/UpdateGuestBook", {
			method: 'post',
			headers: {'Content-Type':'application/json; charset=utf-8'},
			body: JSON.stringify(self.guestBook)
		}).then(function(response) {
			return response.json();
		}).then(function(return_data){
			if(return_data == ""){
				console.log("The guest book information has been updated successfully.");
			}else{
				console.log("There is an issue updating the guest book information.");
			}
		});
	}
  },
  mounted: function () {
	this.getGuestBook();
  }
})

</script>
</body>
</html>

If we see above code, the first important thing we have to do is to include the Vue library. Simply include the Vue JavaScript link into the HTML head tag or at the end of body tag. It depends on your preference. If you include at the very bottom of your body tag, you have to make sure to include this library script first before calling any reference into this library. Otherwise, you will get a script reference error not found.

When we create our first Vue app, we have to make sure the element id exists, otherwise it will not work when you try. We can define it by specifying the element id tag which use the keyword el.

var app = new Vue({
	el: '#guestbook-app',
	.....
})

Because we want to populate the data from the server, we need to set an empty data to our initial app, this can be done by specifying the empty data symbol to Vue data tag. Here is the code.

data: {
	guestBook: []
}

The next step is to create two methods which will cover the Get and Update functions. Note: because I only want to showcase how the form input binding works in Vue, I will not cover any other function like New, Delete or Get all records method in this tutorial. Let see the first getGuestBook method. The method will pass a JSON object data by specifying hardcoded GuestID = 1. It will use the built-in fetch JavaScript function to post the JSON data to Web API URL and get the JSON data object. If you notice when returning the JSON data object we map it back to guestbook data variable. This get method will be invoked as we specify the mounting method in our Vue App. If you see in our mounted method, I have called the following method function.

mounted: function () {
	this.getGuestBook();
}

So how does the binding work in the form inputs? If we see carefully on the HTML tag of each input, you will notice that I have included keyword v-model which will be presented by the data object guestBook field property which will contain property FirstName, LastName, and Email. You have to make sure you have entered the correct property name otherwise you will get an undefined value.

<input type="text" v-model="guestBook.FirstName"/></div>

The next method will be the updateGuestBook. The concept of the method would be pretty similar to get method, the only difference is the URL of the Web API and the automatic of object binding is automatically done for you without you have to manually populate the JSON data. Remember in the old days if you want to perform an update, you have to manually set the value of each text box and manually add it to the object value. The Vue script will automatically map each model property field value for you. You can see, I just need to specify the following code. Note: the self variable represents the this definition which is the Vue app itself.

//auto populate the JSON object for you
body: JSON.stringify(self.guestBook)

//old method, just an example only to compare.
var jsonData: {
	GuestID: document.getElementById(guestTextID).value,
	FirstName: document.getElementById(firstNameTextID).value,
	LastName: document.getElementById(lastNameTextID).value,
	Email: document.getElementById(emailTextID).value,
}

The update method will then be attached to the update button to perform an update of the record. If you have any question regarding with this tutorial, feel free to post your comment below.

Comments

Tinashe
17 Feb, 2019
Great job! :)
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles