Tuesday 5 December 2023

CRUD opration using PHP API & DOT NET MVC

 


PHP API :

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Max-Age: 3600");
include "conn.php";
$json = file_get_contents("php://input");
$obj= json_decode($json,true);
$method=$_SERVER['REQUEST_METHOD'];
if(strstr($_SERVER['REQUEST_URI'],'?'))
{
    $path1=explode('?',$_SERVER['REQUEST_URI']);
    $path =explode('=',$path1[1]);
}
switch ($method) {
    case 'GET' :
        if(isset($path[1]) && is_numeric($path[1]))
        {
            $result=mysqli_query($conn,"Select * from class where CID='$path[1]'");
            if (mysqli_num_rows($result) > 0) {
                while($row = mysqli_fetch_assoc($result)) {
                  $data=json_encode($row);
                }
                echo $data;
            }
            else
            {
                echo json_encode("result not found.");
            }
        }
        else
        {
            $result=mysqli_query($conn,"Select * from class");
        if (mysqli_num_rows($result) > 0) {
            while($row[] = mysqli_fetch_assoc($result)) {
              $data=json_encode($row);
            }
            echo $data;
        }
        else
        {
            echo json_encode("result not found.");
        }
        }
        break;
    case 'POST':
        $cNAME=$obj["CNAME"];
    $result=mysqli_query($conn,"INSERT INTO `class`(`CNAME`) VALUES ('$cNAME')");
    if($result)
    {
        echo json_encode("Data Inserted successfully.");
    }
    else
    {
        echo json_encode("Something went wrong.");
    }
        break;
        case 'PUT':
            $cID=$obj["CID"];
            $CNAME=$obj["CNAME"];
            $result=mysqli_query($conn,"UPDATE `class` SET  `CNAME`='$CNAME'   WHERE CID='$cID'");
            if($result)
            {
                echo json_encode("Data Updated successfully.");
            }
            else
            {
                echo json_encode("Something went wrong.");
            }  
            break;
            case 'DELETE':
                if(strstr($_SERVER['REQUEST_URI'],'?'))
                {
                $path2=explode('?',$_SERVER['REQUEST_URI']);
                $path3 =explode('=',$path2[1]);
                }
                $cID= $path3[1];
                $result=mysqli_query($conn,"delete from  `class` where CID='$cID'");
                if($result)
                {
                    echo json_encode("Data deleted successfully.");
                }
                else
                {
                    echo json_encode("Something went wrong.");
                }
                break;
    default:

        echo 'Something went wrong.';

        break;

}
mysqli_close($conn);
?>


DOT NET MVC:

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Security.Policy;

using System.Text;

using System.Web;

using System.Web.Mvc;

using WebApplication9.Models;

using System.Threading.Tasks;


namespace WebApplication9.Controllers

{

    public class ClassController : Controller

    {

        // GET: Class

        public async Task<ActionResult> Index()

        {

            List<ClassVM> result = new List<ClassVM>();

            using (var client = new HttpClient())

            {

                using (var response = await client.GetAsync("http://localhost:8080/CMS/API/Test"))

                {

                    if (response.IsSuccessStatusCode)

                    {

                        var productJsonString = await response.Content.ReadAsStringAsync();


                         result = JsonConvert.DeserializeObject<ClassVM[]>(productJsonString).ToList();

                        

                    }

                }

            }

            return View(result);


        }

        [HttpGet]

        public ActionResult Create()

        {

            ClassVM cvm = new ClassVM();

            return View(cvm);

        }

        [HttpPost]

        public async Task<ActionResult> Create(ClassVM vm)

        {

            using (var client = new HttpClient())

            {

                var serializedProduct = JsonConvert.SerializeObject(vm);

                var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");

                var result = await client.PostAsync("http://localhost:8080/CMS/API/Test", content);

            }

            return RedirectToAction("Index");

        }

        [HttpGet]

        public async Task<ActionResult> Edit(int id)

        {

            ClassVM result = new ClassVM();

            using (var client = new HttpClient())

            {

                using (var response = await client.GetAsync("http://localhost:8080/CMS/API/Test?CID="+id))

                {

                    if (response.IsSuccessStatusCode)

                    {

                        var productJsonString = await response.Content.ReadAsStringAsync();


                        result = JsonConvert.DeserializeObject<ClassVM>(productJsonString);


                    }

                }

            }

            return View(result);

        }

        [HttpPost]

        public async Task<ActionResult> Edit(ClassVM vm)

        {

            using (var client = new HttpClient())

            {

                var serializedProduct = JsonConvert.SerializeObject(vm);

                var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");

                var result = await client.PutAsync("http://localhost:8080/CMS/API/Test", content);

            }

            return RedirectToAction("Index");

        }

        [HttpGet]

        public async Task<ActionResult> Delete(int id)

        {

            using (var client = new HttpClient())

         {

                var result = await client.DeleteAsync("http://localhost:8080/CMS/API/Test?CID="+id);

            }

            return RedirectToAction("Index");

        }

    }

}



No comments:

Post a Comment