Skip to content

Instantly share code, notes, and snippets.

@muratbaseren
Last active July 26, 2023 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratbaseren/aa59270008e6287962a70fc1f3151a6d to your computer and use it in GitHub Desktop.
Save muratbaseren/aa59270008e6287962a70fc1f3151a6d to your computer and use it in GitHub Desktop.
Model Kullanarak Birbiri ile Bağlantılı JQuery ile Dolan DropDownList Doldurma
// Gerekli açıklamalar kod içerisinde yapılmıştır. Veritabanı kullanılmadan,
// Fake olarak modellenmiştir. Country ve City class'larında veri üreten metotlara yer verilmiştir.
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace WebApplication8.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// Sayfaya DropDownList verilerinizi model ile göndermek isterseniz.
// IndexViewModel tipindeki modelimizde 2 adet SelectList tipinde property tanımlıyoruz.
// Verilerimiz bu property ler ile View'a gidecektir.
// Gönderdiğimiz veriler DropDownList de kullanılacağı için SelectList e çevirmeyi unutmuyoruz.
// Ülke seçildikten sonra şehir seçileceği için sadece ülke verisi doldurulur.
SelectList countriesData = new SelectList(DBContext.CountriesTable, "Id", "CountryName");
// Seçili gelmesi istenilen DropDownList item'larının değerleri
// bu şekilde gönderilebilir.
IndexViewModel model = new IndexViewModel()
{
SelectedCountryId = -1,
SelectedCityId = -1,
CountriesData = countriesData,
// Başlangıçta şehir verisi yoktur ama kayıt düzenleme yaparsanız burayı da doldurunuz.
CitiesData = new SelectList(new List<City>())
};
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
// Model içinde gönderdiğimiz citiesData ve countriesData verileri View'dan alınmaz.
// POST işlemi sonrasında aynı sayfa tekrar açılacak ise,
// Model e değerlerini tekrar yüklemeliyiz.
// Bu verileri bir Cache mekanizmasından yükleyerek sürekli DB ye gitme gerekliliği kaldırabilirsiniz.
// Performans açısından da daha doğru olacaktır. Tabii veriler sürekli değişmiyorsa..!
SelectList countriesData = new SelectList(DBContext.CountriesTable, "Id", "CountryName");
SelectList citiesData = new SelectList(DBContext.CitiesTable, "Id", "CityName");
model.CitiesData = citiesData;
model.CountriesData = countriesData;
return View(model);
}
// id : CountryId
public JsonResult GetCitiesByCountry(int id)
{
return Json(
DBContext.CitiesTable.Where(ci => ci.CountryId == id).ToList(),
JsonRequestBehavior.AllowGet);
}
}
}
namespace WebApplication8
{
public class City
{
public int Id { get; set; }
public string CityName { get; set; }
public int CountryId { get; set; }
// 10 adet şehir içeren list üreten bir metot.
public static List<City> GetFakeCities()
{
return new List<City>()
{
new City() { Id=11, CityName = "Leicester", CountryId=0 },
new City() { Id=12, CityName = "Sunderland", CountryId=0 },
new City() { Id=13, CityName = "Bath", CountryId=1 },
new City() { Id=14, CityName = "Leeds", CountryId=1 },
new City() { Id=15, CityName = "Dallas", CountryId=2 },
new City() { Id=16, CityName = "Lancaster", CountryId=2 },
new City() { Id=17, CityName = "Tampa", CountryId=2 },
new City() { Id=18, CityName = "Christchurch", CountryId=2 },
new City() { Id=19, CityName = "Laredo", CountryId=3 },
new City() { Id=20, CityName = "Indianapolis", CountryId=3 },
};
}
}
public class Country
{
public int Id { get; set; }
public string CountryName { get; set; }
// 4 adet ülke içeren list üreten bir metot.
public static List<Country> GetFakeCountries()
{
return new List<Country>()
{
new Country() { Id= 0, CountryName = "Morocco" },
new Country() { Id= 1, CountryName = "American Samoa" },
new Country() { Id= 2, CountryName = "New Zealand" },
new Country() { Id= 3, CountryName = "Channel Islands" },
};
}
}
// DBContext i temsil eden fake bir class
// Fake olarak ürettiğim verileri bana sunacak.
// Sizin verileriniz DB ya da istediğiniz kaynaktan gelebilir.
public static class DBContext
{
public static List<Country> CountriesTable = Country.GetFakeCountries();
public static List<City> CitiesTable = City.GetFakeCities();
}
// Index sayfasında kullanacağımız view modelimiz
public class IndexViewModel
{
// Sayfa GET anında bu property ler ile seçili ülke/şehir Id gönderilebilir
// ya da POST işleminde seçili ülke/şehir Id elde edilebilir.
// MVC kendisi seçili değeri bize bu property 'lere dolduracaktır.
public int SelectedCountryId { get; set; }
public int SelectedCityId { get; set; }
public SelectList CitiesData { get; set; }
public SelectList CountriesData { get; set; }
}
}
@model IndexViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DropDownList Mevzusu</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h2>Drop Down Sample</h2>
<hr />
@* POST işlemi için BeginForm metodu ile Form elementi oluşturmayı unutmuyoruz.. *@
@using (Html.BeginForm())
{
<div class="col-md-12">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Country :</label>
<div class="col-md-5">
@Html.DropDownListFor(m => m.SelectedCountryId, Model.CountriesData, "Lütfen Seçiniz", new { @class = "dropdown form-control" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">City :</label>
<div class="col-md-5">
@Html.DropDownListFor(m => m.SelectedCityId, Model.CitiesData, "Lütfen Seçiniz", new { @class = "dropdown form-control" })
</div>
</div>
<hr />
<div class="col-md-7 text-right">
<button type="submit" class="btn btn-success">Gönder</button>
<hr />
<div class="alert alert-success text-center">
<div><b>Selected Country : </b>@Model.SelectedCountryId</div>
<div><b>Selected City : </b>@Model.SelectedCityId</div>
</div>
</div>
</div>
</div>
}
<script>
$("#SelectedCountryId").change(function () {
var ddlCountry = $(this);
var countryId = ddlCountry.val();
if (countryId != "") {
$.ajax({
method: "GET",
url: '@Url.Action("GetCitiesByCountry","Home")' + '/' + countryId,
beforeSend: function () {
// ajax isteği öncesi şehirler silinir.
$("#SelectedCityId option").not(":first").remove();
}
}).done(function (result) {
console.log(result);
// json formatında ülkeye ait şehirler gelir..
// her biri için option elementi oluşturulur
// şehirler(id=SelectedCityId) dropdownlist e eklenir.
for (var i = 0; i < result.length; i++) {
var city = result[i];
var opt = $("<option></option>");
opt.val(city.Id);
opt.text(city.CityName);
$("#SelectedCityId").append(opt);
}
});
} else {
$("#SelectedCityId option").not(":first").remove();
}
});
</script>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment