Wednesday, June 28, 2023

Full Stack Web App using Vue JS, .NET Core Web API and Microsoft SQL Server

 Please check out the below video to understand the tutorial much better.

 

In this tutorial, we will learn how to build a simple “To Do” application from scratch using

Vue JS as the front end, .NET Core Web API as the backend, and Microsoft SQL server as the database.

Ø Install Node JS:

https://nodejs.org/en/download

Ø  Install SQL Server Management Studio (SSMS) to interact with SQL Server.

https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16

 

Ø Install Visual Studio Community (Free for learning purpose only).

https://visualstudio.microsoft.com/vs/community/

 

Ø Create the database table and insert couple of records:

 







Ø Open Visual Studio and create the .NET Core Web API Project.


Ø Install Newtonsoft.Json Nuget package.


Ø Program.cs :

using Newtonsoft.Json.Serialization;

 

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

//JSON Serializer

builder.Services.AddControllers().AddNewtonsoftJson(options=>

options.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore).AddNewtonsoftJson(

    options=>options.SerializerSettings.ContractResolver=new DefaultContractResolver());

var app = builder.Build();

//Enable CORS

app.UseCors(c => c.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());

// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI();

}

app.UseAuthorization();

app.MapControllers();

app.Run();

 

 

Ø Add connection strings in appsetting.json:

{

  "ConnectionStrings": {

    "todoAppDBCon": "<<Your SQL Server Connection String here>>"

  },

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "AllowedHosts": "*"

}

Ø Create a new Controller TodoAppController.cs:

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System.Data;

using System.Data.SqlClient;

using System.Security.AccessControl;

namespace WebApplication1.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class TodoAppController : ControllerBase

    {

        private IConfiguration _configuration ;

        public TodoAppController(IConfiguration configuration)

        {

            _configuration = configuration;

 

        }

 

        [HttpGet]

        [Route("GetNotes")]

        public JsonResult GetNotes()

        {

            string query = "select * from dbo.Notes";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using(SqlConnection myCon=new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using(SqlCommand myCommand = new SqlCommand(query,myCon))

                {

                    myReader=myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult(table);

        }

 

        [HttpPost]

        [Route("AddNotes")]

        public JsonResult AddNotes([FromForm] string newNotes)

        {

            string query = "insert into dbo.Notes values(@newNotes)";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using (SqlConnection myCon = new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using (SqlCommand myCommand = new SqlCommand(query, myCon))

                {

                    myCommand.Parameters.AddWithValue("@newNotes", newNotes);

                    myReader = myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult("Added Successfully");

        }

 

        [HttpDelete]

        [Route("DeleteNotes")]

        public JsonResult DeleteNotes(int id)

        {

            string query = "delete from dbo.Notes where id=@id";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using (SqlConnection myCon = new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using (SqlCommand myCommand = new SqlCommand(query, myCon))

                {

                    myCommand.Parameters.AddWithValue("@id", id);

                    myReader = myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult("Deleted Successfully");

        }

 

    }

}

 

Ø For Vue JS project, just create a file index.html and add below content:

 <div id="app">

   
    <h2>Todo App</h2>
    <input id="newNotes"/>&nbsp;
    <button @click="addNewNotes()">Add Notes</button>
    <p v-for="note in notes">
        <b>* {{note.description}}</b>&nbsp;
        <button @click="deleteNotes(note.id)">Delete Notes</button>
    </p>
</div>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js"
integrity=
"sha512-uMtXmF28A2Ab/JJO2t/vYhlaa/3ahUOgj1Zf27M5rOo8/+fcTUVH0/E0ll68njmjrLqOBjXM3V9NiPFL5ywWPQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script type="module">
  import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
  const API_URL="http://localhost:5038/";
  createApp({
    data() {
      return {
        title:"Todo App",
        notes:[]
      }
    },methods:{
        async refreshData(){
            axios.get(API_URL+"api/todoapp/GetNotes").then(
                (response)=>{
                    this.notes=response.data;
                }
            )
        },
        async addNewNotes(){
            var newNotes=document.getElementById("newNotes").value;
            const formData=new FormData();
            formData.append("newNotes",newNotes);

            axios.post(API_URL+"api/todoapp/AddNotes",formData).then(
                (response)=>{
                    this.refreshData();
                    alert(response.data);
                }
            )
        },
        async deleteNotes(id){
           

            axios.delete(API_URL+"api/todoapp/DeleteNotes?id="+id).then(
                (response)=>{
                    this.refreshData();
                    alert(response.data);
                }
            )
        }
    },mounted:function(){
        this.refreshData();
    }
  }).mount('#app')
</script>

No comments:

Post a Comment

Full Stack Web App using Vue JS, .NET Core Web API and Microsoft SQL Server

 Please check out the below video to understand the tutorial much better.   In this tutorial, we will learn how to build a simple “To Do...