Now day when I search related to Mvc 3.0. I have found Question So many forums that how to get data on basis of dropdown value change. suppose I have dropdown for country when I change value from country drop down I need other info display in view which need to collect from sql database. now let’s play with this question
I have create one simple view
which contain only one drop down
// Comment @{ ViewBag.Title = "Index"; }Index
Select List:@Html.DropDownList("dplist", (SelectList)ViewBag.DpList)
now let’s look my controller
// Comment using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Controllers { public class FilterController : Controller { // // GET: /Filter/ public ActionResult Index() { initilization(); return View(); } public void initilization() { ListLiList = new List (); AddItemInlist("One", 1, LiList, false); AddItemInlist("Two", 2, LiList, false); AddItemInlist("Three", 3, LiList, true); AddItemInlist("Four", 4, LiList, false); AddItemInlist("Five", 5, LiList, false); ViewBag.DpList = new SelectList(LiList, "Value", "Text"); } public void AddItemInlist(string Key, Int32 value, List addtolist, bool IsSelected) { SelectListItem Li = new SelectListItem(); Li.Text = Key; if (IsSelected) { Li.Selected = true; } Li.Value = value.ToString(); addtolist.Add(Li); } public ActionResult GetData(int id) { //in dplist you will get vaue of dropdown value //on basis of this you can create your logic List LiList = new List (); AddItemInlist("Apple", 1, LiList, false); AddItemInlist("Bannan", 2, LiList, false); return Json(LiList,JsonRequestBehavior.AllowGet); } } }
here main point is that I have create on action getdata using this I am getting data when I change dropdown value
here is Java script which will call when I change dropdown
// Comment <script type="text/javascript"> $(document).ready(function () { $("#dplist").change(function () { var Url = '/Filter/GetData/' + parseInt($(this).val()); $.ajax({ url: Url, type: 'GET', dataType: 'json', contentType: 'application/json', success: function (data) { data = data $.each(data, function (key, value) { //get each value alert(value.Text); alert(value.Value); }); } }); }); }); </script>Here is My Output
No comments:
Post a Comment