sandeep sir

Saturday, 27 June 2015

Bind Drop-down List Using Jquery In MVC

Hello frnds ,In this article i will explain you how to bind dropdown list dynamically with database using jquery(ajax,json).
 There are many ways to bind dropdown in mvc .Here i am using jquery to get data from database and show into dropdown to achieve this i am using ,entity framework 5.0 and sql server 2008.
 I have a country table to explain you .Below is Sql Create Command to create table just copy and paste into your data base

SQL Command 


                                 CREATE TABLE [dbo].[Country](
[Country_ID] [int] IDENTITY(1,1) NOT NULL,
[Country_Name] [varchar](200) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
(
[Country_ID] 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



Now our table is ready to use just before use it ,out some data into table.




Now Create a DAL folder in your root of the project

And create Entity for country table I feel you are aware from entity framework.Now create Controller with name Home. and create following Code .



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication19.DAL;

namespace MvcApplication19.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        private ContryEntities db = new ContryEntities();


        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GetCountry()
        {
            var country = (from c in db.Countries.ToList() select new { Country_ID = c.Country_ID, Country_Name = c.Country_Name });
            return Json(country, JsonRequestBehavior.AllowGet);
        }
    }
}

Now Create View For this controller :



@{
    ViewBag.Title = "Index";
}
<div style="border:1px;width:50%;padding-left:50%;">
<h2>Index</h2>
<select id="ddlCountry" onchange="onCountry(this)" class="form-control">
    <option>Loading.....</option>
</select>
<input type="hidden" id="Country_Name" name="Country_Name" value="1" />
</div>
@section scripts{
<script>

    function onCountry(e) {
        document.getElementById('Country_Name').value = e.value;
    }
    $(document).ready(function () {
        $.ajax({
            cache: true,
            type: "GET",
            url: "/Home/GetCountry",
            success: function (data) {
                $("#ddlCountry").html('');
                $.each(data, function (id, option) {
                    $("#ddlCountry").append($('<option></option>').val(option.Country_ID).html(option.Country_Name));
                });
            }
        });

    });
</script>
    }
Dropdown With Data
Finally Dropdown is bind, i hope u will like it. if any suggestion so plz mention in comment ok thanks.






0 comments:

Post a Comment