Saturday, 15 December 2018

MVC - JSON - Simple CRUD DB First Stored Procedures with no extra component installed

Watch this example on YouTube



1. SQL Table

CREATE TABLE [dbo].[Users](
    [UserID] [int] IDENTITY(1,1) NOT NULL,
    [UserFirstName] [nvarchar](50) NULL,
    [UserLastName] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
    [UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]

GO

2. Stored Procedures

CREATE PROCEDURE [dbo].[Users_Update]
    @UserID int,
    @UserFirstName nvarchar(50),
    @UserLastName nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Update Users Set UserFirstName = @UserFirstName, UserLastName = @UserLastName
        Where UserId = @UserID


END

CREATE PROCEDURE [dbo].[Users_SelectByID]
    @UserID Int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT * FROM USERS WHERE UserID = @UserID
END

CREATE PROCEDURE [dbo].[Users_SelectAll]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT * FROM Users
END

CREATE PROCEDURE [dbo].[Users_Insert]
    @UserFirstName nvarchar(50),
    @UserLastName nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Users(UserFirstName, UserLastName) Values(@UserFirstName, @UserLastName)
    Return 0
END

CREATE PROCEDURE [dbo].[Users_Delete]
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM Users WHERE UserID = @UserID
END

3. Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Styles.Render("~/Content/themes/base/jquery-ui.css")
    @*@Scripts.Render("~/bundles/jquery")*@
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

4. Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        private CompanyEntities db = new CompanyEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public JsonResult GetUserList()
        {
            IEnumerable<Users_SelectAll_Result> model = db.Users_SelectAll();
            return Json(model);
        }
        public JsonResult SaveUser(Users_SelectByID_Result usr)
        {
            db.Users_Insert(usr.UserFirstName, usr.UserLastName);
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Home");
            return Json(new { Url = redirectUrl });
        }
        public JsonResult UpdateUser(Users_SelectByID_Result usr)
        {
            db.Users_Update(usr.UserID, usr.UserFirstName, usr.UserLastName);
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Home");
            return Json(new { Url = redirectUrl });
        }
        public JsonResult DeleteUser(int UserID)
        {
            db.Users_Delete(UserID);
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Home");
            return Json(new { Url = redirectUrl });
        }

    }
}
5. Index.chtml


@{
    ViewBag.Title = "Home Page";
}

<div id="UserList" onload="LoadUsers();">

</div>
<div class="AddNewUser">
    @Html.Label("Add new user")
</div>
<div id="AddUser" style="display:none;">
    @Html.Label("First Name")
    @Html.TextBox("FirstName", null)
    <br />
    @Html.Label("Last Name")
    @Html.TextBox("LastName", null)
    <br />
    <input type="submit" onclick="AddUser(event)" value="SAVE" id="btnSaveUser" />
</div>

<div id="EditUser" style="display:none;">
    @Html.Label("First Name")
    @Html.TextBox("FirstNameEdit", null)
    <br />
    @Html.Label("Last Name")
    @Html.TextBox("LastNameEdit", null)
    <br />
    @Html.Hidden("UserIDEdit")
    <input type="submit" onclick="UpdateUser(event)" value="SAVE" id="btnSaveUser" />
</div>

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            LoadUsers();
            $('#AddUser').dialog({
                autoOpen: false,
                height: 200,
                width: 500,
                modal: false
            });
            $(".AddNewUser").click(function (e) {
                e.stopPropagation();
                $('#AddUser').dialog('option', 'title', 'Add User');
                $('#AddUser').dialog('open');
            });
            $('#EditUser').dialog({
                autoOpen: false,
                height: 200,
                width: 500,
                modal: false
            });
        });

        function LoadUsers() {
            var users = {};
            users.url = '@Url.Action("GetUserList", "Home")';
            users.type = 'POST';
            users.dataType = 'json';
            users.contentType = 'application/json';
            users.success = function (Users) {
                if (Users.length > 0) {
                    $('#UserList').append('<table>');
                    $('#UserList').append('<tr><th>First Name</th><th>Last Name</th><th></th><th></th></tr>');
                    $.each(Users, function (i, User) {
                        $('#UserList').append('<tr><td class="FirstName">'
                            + User.UserFirstName + '</td><td class="LastName">'
                            + User.UserLastName + '</td><td><input type="hidden" id="hid" value="'
                            + User.UserID + '" /> <input type="submit" value="EDIT" name="btn" id="btnEdit" onclick="EditUser(this);"</td><td><a href="#" id="btnDelete" onclick="DeleteUser(this);">DELETE</a></td></tr>');

                    });

                    $('#UserList').append('</table>');
                }
            };
            $.ajax(users);
        }
        function AddUser(e) {
            var UserRec = {};
            UserRec.UserFirstName = $('#FirstName').val();
            UserRec.UserLastName = $('#LastName').val();
            $.ajax({
                url: '@Url.Action("SaveUser", "Home")',
                type: 'POST',
                data: '{usr: ' + JSON.stringify(UserRec) + '}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    if (response.ErrorMessage != null) {
                        alert(response.ErrorMessage);
                    }
                    else {
                        window.location.href = response.Url;
                    }
                },
                error: function (xhr, status, error) {
                    var el = document.createElement('html');
                    el.innerHTML = xhr.responseText;
                    alert(el.getElementByTagName('title')[0].innerText);
                }
           
            });
        }
        function EditUser(e) {
            var row = $(e).closest('tr');
            var UserID = row.find($("[id*=hid]")).val();
            var FirstName = row.find(".FirstName").text();
            var LastName = row.find(".LastName").text();
            $('#FirstNameEdit').val(FirstName);
            $('#LastNameEdit').val(LastName);
            $('#UserIDEdit').val(UserID);
            $('#EditUser').dialog('option', 'title', 'Edit User');
            $('#EditUser').dialog('open');
        }
        function UpdateUser(e) {
            var UserRec = {};
            UserRec.UserFirstName = $('#FirstNameEdit').val();
            UserRec.UserLastName = $('#LastNameEdit').val();
            UserRec.UserID = $('#UserIDEdit').val();
            $.ajax({
                url: '@Url.Action("UpdateUser", "Home")',
                type: 'POST',
                data: '{usr: ' + JSON.stringify(UserRec) + '}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    if (response.ErrorMessage != null) {
                        alert(response.ErrorMessage);
                    }
                    else {
                        window.location.href = response.Url;
                    }
                },
                error: function (xhr, status, error) {
                    var el = document.createElement('html');
                    el.innerHTML = xhr.responseText;
                    alert(el.getElementByTagName('title')[0].innerText);
                }
            });
        }
        function DeleteUser(e) {
            var row = $(e).closest('tr');
            var UserID = row.find($("[id*=hid]")).val();
            $.ajax({
                url: '@Url.Action("DeleteUser", "Home")',
                type: 'POST',
                data: JSON.stringify({ UserID: UserID }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    if (response.ErrorMessage != null) {
                        alert(response.ErrorMessage);
                    }
                    else {
                        window.location.href = response.Url;
                    }
                },
                error: function (xhr, status, error) {
                    var el = document.createElement('html');
                    el.innerHTML = xhr.responseText;
                    alert(el.getElementByTagName('title')[0].innerText);
                }
            });
        }
    </script>   
}

No comments:

Post a Comment