본문 바로가기
ASP.NET MVC

ASP.NET MVC] Vue.js 로 CRUD 구현

by Fastlane 2022. 1. 6.
728x90
반응형

Index.cshtml

@model IndexViewModel;

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <div id="app">
        <h1 class="display-4">User: {{user.name}}</h1>
        <h2 class="display-4">Last name: {{user.lastName}}</h2>
        <h2 class="display-4">Username: {{user.username}}</h2>
        <hr />
        <div v-if="friends_list.length > 0">
            <h2 class="display-4">Friends!</h2>
            <ul class="list-group list-group-flush" v-for="friend in friends_list">
                <a v-on:click="removeFriend(friend.username, friend.lastName, friend.name)" class="list-group-item list-group-item-action">
                    User: {{friend.name}}, Last Name {{friend.lastName}}, Username: {{friend.username}}
                </a>
            </ul>
        </div>

        <hr />
        <h1 class="display-4">Create new friend</h1>
        <div class="input-group mb-3">
            <input type="text" class="form-control" v-model="new_friend.name" placeholder="Name" aria-label="Name" aria-describedby="basic-addon1">
        </div>
        <div class="input-group mb-3">
            <input type="text" class="form-control" v-model="new_friend.lastName" placeholder="lastName" aria-label="lastName" aria-describedby="basic-addon1">
        </div>
        <div class="input-group mb-3">
            <input type="text" class="form-control" v-model="new_friend.userName" placeholder="userName" aria-label="userName" aria-describedby="basic-addon1">
        </div>
        <button v-on:click="addFriend" type="button" class="btn btn-dark">Add user</button>
        <hr />

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            user: {
                username: '@Model.User.Username',
                lastName: '@Model.User.LastName',
                name: '@Model.User.Name'
            },
            new_friend: {
                username: "",
                lastName: "",
                name: ""
            },
            friends_list: []
        },
        mounted: function () {
            let friendList = '@Html.Raw(Json.Serialize(Model.FriendList))';
            this.friends_list = JSON.parse(friendList);
        },
        methods: {
            getFriendsList: function () {
                let self = this;
                fetch('@Url.Action("GetFriendsList", "Home")')
                    .then(response => response.json())
                    .then(data => self.friends_list = data);
            },
            addFriend: function () {
                let self = this;
                fetch('@Url.Action("InsertNewFriendInMemory", "Home")', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(self.new_friend),
                })
                .then(response => response.json())
                .then(data => {
                    if (data)
                        self.getFriendsList();
                })
            },
            removeFriend: function (username, lastName, name) {
                let self = this;
                let deleteParameters = {
                    username: username,
                    lastName: lastName,
                    name: name
                };
                fetch('@Url.Action("RemoveFriend", "Home")', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(deleteParameters)
                })
                .then(response => response.json())
                .then(data => {
                    if (data)
                        self.getFriendsList();
                })
            }
        }
    })

</script>

 

HomeController.cs

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using VUE.Models;

namespace VUE.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            var friendsList = new List<User>
            {
                new User
                {
                    LastName = "Ford",
                    Name = "Henry",
                    Username = "henryford121"
                },
                new User
                {
                    LastName = "Montgo",
                    Name = "Suzzie",
                    Username = "mongosus"
                },
                new User
                {
                    LastName = "Rivera",
                    Name = "Luis",
                    Username = "starraiden"
                }
            };
            TempData["TempDataFriendsList"] = JsonConvert.SerializeObject(friendsList);
            var model = new IndexViewModel
            {
                User = new User
                {
                    LastName = "Rivera",
                    Name = "Genesis",
                    Username = "genesisrrios"
                },
                FriendList = friendsList
            };

            return View(model);
        }
        [HttpPost]
        public bool InsertNewFriendInMemory([FromBody] User friend)
        {
            if (friend == default || !TempData.ContainsKey("TempDataFriendsList")) return false;
            var tempData = TempData["TempDataFriendsList"];
            var deserializedData = JsonConvert.DeserializeObject<List<User>>((string)tempData);
            deserializedData.Add(friend);
            TempData["TempDataFriendsList"] = JsonConvert.SerializeObject(deserializedData);
            return true;
        }
        public List<User> GetFriendsList()
        {
            var tempData = TempData["TempDataFriendsList"];
            TempData.Keep();
            var deserializedData = JsonConvert.DeserializeObject<List<User>>((string)tempData);
            return deserializedData;
        }
        [HttpDelete]
        public bool RemoveFriend([FromBody] User friend)
        {
            if (friend == default || !TempData.ContainsKey("TempDataFriendsList")) return false;
            var tempData = TempData["TempDataFriendsList"];
            var deserializedData = JsonConvert.DeserializeObject<List<User>>((string)tempData);
            deserializedData.Remove(friend);
            TempData["TempDataFriendsList"] = JsonConvert.SerializeObject(deserializedData);
            return true;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

 

간단한 app이라면 위와 같이 <script>태그만 추가하여 vue.js 사용이 가능하겠지만, app 사이즈가 커짐에 따라, View파일에 scripts를 작성하는 것은 복잡하고, 관리하기 어려워진다. 

 

좀 더 복잡한 앱을 구성하려면, Vue NPM 패키지를 사용하는 것이 좋다. 

npm패키지와 CLI를 사용하기 위해서는 Node.js 8.11 이상을 설치해야 한다. 

 

 

728x90
반응형

댓글