I keep receiving "NullReferenceException" error when i click button in my view. I created a list of the cities class and keep the data in TempData["cities"]. When i click the button, i want to redirect the page to the city name view and keep that city instance in a new TempData but the code doesnt even go in to the foreach loop. Can you help me?
[The photo of my code is here.] [1]: https://i.stack.imgur.com/zopfc.png
public IActionResult CitiesOnMap()
{
List<City> cities = new List<City>();
cities.Add(new City { CityName = "Hatay", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Konya", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "İstanbul", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "İzmir", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Muğla", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Antalya", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Bursa", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Manisa", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Mersin", Latitude = 123, Longtitude = 435 });
cities.Add(new City { CityName = "Ankara", Latitude = 123, Longtitude = 435 });
TempData["cities"] = cities;
return View();
}
[HttpPost]
public IActionResult CitiesOnMap(string SelectedCity)
{
foreach (var redirectedCity in TempData["cities"] as List<MVC.Models.City>)
{
Console.WriteLine("bumbum");
if (String.Equals(redirectedCity.CityName, SelectedCity))
{
TempData["selectedCity"] = redirectedCity;
return RedirectToAction(redirectedCity.CityName , "City");
}
}
return RedirectToAction(SelectedCity, "City"); ;
}
.cshtml view:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "CitiesOnMap";
}
<div class="text-center pt-5">
<h1 class="display-4 pb-2 ">LET'S SEE THE CITIES!</h1>
<p class="pb-3">Now, Please Choose A City You Want to See on Map.</p>
<h3> @TempData["SelectedMap"] </h3>
<div class="text-center mx-auto pt-5">
<form asp-action="CitiesOnMap" asp-controller="City" method="post">
<div class="row">
<div class="col-9 mx-auto">
<select id="drpEmpList" name="SelectedCity" class="form-control">
<option disabled selected hidden>Choose a City </option>
@foreach (var name in TempData["cities"] as List<MVC.Models.City>)
{
<option>@name.CityName </option>
}
</select>
@{ TempData.Keep("cities"); }
<input type="hidden" />
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4">
<input type="submit" name="btnSubmit" value="Let's See" class="btn btn-success btn-lg" />
</div>
</div>
</form>
</div>
</div>
And now I'm getting HTTP ERROR 500