Wednesday, 14 March 2018

MVC - json - Create table dynamically

Watch this example on YouTube


 
1. Stored procedure

USE [Company]
GO
/****** Object:  StoredProcedure [dbo].[Users_SelectAll]    Script Date: 2018-03-14 8:03:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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

2.  Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCJsonT.Models;

namespace MVCJsonT.Controllers
{
    public class HomeController : Controller
    {
        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 GetUsers()
        {
            IEnumerable<Users_SelectAll_Result> model = db.Users_SelectAll().ToList();
            return Json(model);
        }
    }
}

3. View

<div id="UserList"></div>

@section Scripts{
    <script>
        $(document).ready(function () {
            LoadUsers();
        });

        function LoadUsers() {
            var users = {};
            users.url = '@Url.Action("GetUsers", "Home")';
            users.type = "POST";
            users.dataType = "json";
            users.contentType = "application/json";
            users.success = function (Users) {
                if (Users.length > 0) {
                    $('#UserList').append('<tr><th>First Name</th><th>Last Name</th></tr>')
                    $.each(Users, function (i, User) {
                        $('#UserList').append('<tr><td>' + User.FirstName + '</td><td>' + User.LastName + '</td></tr>')
                    });
                }
            };
            $.ajax(users);
        }
    </script>   
}

No comments:

Post a Comment