Thursday, 12 October 2017

MVC - Json - Populate Drop Down List (select) using Json


Watch this example on YouTube



1. SQL



USE [Test]
GO
/****** Object:  Table [dbo].[Product]    Script Date: 2017-10-12 9:40:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[Product] ON

GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (1, N'Monitor')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (2, N'Computer')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (3, N'Mouse')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (4, N'Laptop')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (5, N'TV')
GO
SET IDENTITY_INSERT [dbo].[Product] OFF
GO
/****** Object:  StoredProcedure [dbo].[GetProducts]    Script Date: 2017-10-12 9:40:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetProducts]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Select * from Product
END

GO
2. Controller

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

namespace MVCJsonDropDownList.Controllers
{
    public class HomeController : Controller
    {
        TestEntities db = new TestEntities();

        public JsonResult LoadProducts()
        {
            IEnumerable<GetProducts_Result> res = db.GetProducts();
            return Json(res.Select(x => new
            {
                ID = x.ProductID,
                Name = x.ProductName
            }));
        } 



3. View

<select id="Product">
    <option></option>
</select>

<input type="submit" value="Load Products" name="btn" id="btnClick" />

 

4. View - JavaScript
@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var d = {};
                d.url = '@Url.Action("LoadProducts", "Home")';
                d.type = "POST";
                d.dataType = "json";
                d.contentType = "application/json";
                d.success = function (r) {
                    $("#Product").empty();
                    $("#Product").prepend("option value='' selected='selected'></option>");
                    for (var i = 0; i < r.length; i++) {
                        $("#Product").append('<option value="' + r[i].ID + '">' + r[i].Name + '</option>');               
                    }
                };
                $.ajax(d);
            });
        });
    </script>   
}

No comments:

Post a Comment