0

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

Mertcan
  • 19
  • 3
  • 1
    I suggest you *start* by casting instead of using `as` - see https://codeblog.jonskeet.uk/2013/09/19/casting-vs-quot-as-quot-embracing-exceptions/ – Jon Skeet Aug 18 '21 at 11:16
  • did you check what exactly exists inside of `TempData`? Is there present `cities` is desired format? – demo Aug 18 '21 at 11:17
  • Console.WriteLine("bumbum") :~| Btw, I would suggest you to insert the exeption message – Dorin Baba Aug 18 '21 at 11:17
  • @demo how can i check it? I'm beginner level :/ – Mertcan Aug 18 '21 at 11:28
  • Set breakpoint on that line and just check during that redirect :) – demo Aug 18 '21 at 11:32
  • What do you expect to be calling your parameterless `CitiesOnMap` method? – Jon Skeet Aug 18 '21 at 11:39
  • @JonSkeet I used that parameter to get selected city from the dropdown. Do I need a class parameter to use TempData["cities"] in my HttpPost method? – Mertcan Aug 18 '21 at 11:42
  • No, I'm not asking about a *parameter*, I'm asking about the `CitiesOnMap` method that doesn't *have* a parameter. The first method you've shown. How is that being called? (It's not being called from the second method.) It's not clear to me why you need to use TempData at all - just return the list from that first method, and call the first method from the second method... – Jon Skeet Aug 18 '21 at 11:49
  • @JonSkeet Oh I got it. I'm calling the CitiesOnMap method from another page with RedirectToAction. In that page, user is selecting a map (like google, yandex, openstreet) and after choosing, Coming this page to choose a city to show where it is in a map. That's the idea – Mertcan Aug 18 '21 at 11:52
  • Your question should indicate that then - along with what diagnostic steps you've taken to check that it actually *is* being called, and what you observe in TempData when debugging. – Jon Skeet Aug 18 '21 at 11:55

3 Answers3

1

Are you reading the tempdata in you view html page? if yes, it always returns null for the next request. So you can use TempData.Keep("cities") after reading the data. so it will available for next requests

  • Yes I'm using the list to create dropdown with "option" tag with a for loop. Omg where should I write TempData.Keep("cities") ? In my html page? – Mertcan Aug 18 '21 at 11:48
  • can you share your html code here? – Darga Reddy Aug 18 '21 at 11:59
  • @foreach (var name in TempData["cities"] as List) { } – Mertcan Aug 18 '21 at 12:10
  • @Mertcan: Try solution suggested by @DargaReddy. Add @{ `TempData.Keep("cities"); }` to the first line (for example) of your `.cshtml`. This will solve your problem. – Jackdaw Aug 18 '21 at 12:14
  • Add this @{ TempData.Keep("cities"); } next to anywhere in the html – Darga Reddy Aug 18 '21 at 12:14
  • When I added @{ TempData.Keep("cities"); }, now I'm getting HTTP ERROR 500 ???? I really can't understand :( @Jackdaw – Mertcan Aug 18 '21 at 12:17
  • @Mertcan: This should not happen. Add code of your view `.cshtml` to the post, please. – Jackdaw Aug 18 '21 at 12:18
  • I added. Can you check? @Jackdaw – Mertcan Aug 18 '21 at 12:21
  • @Mertcan: Put `TempData.Keep("cities");` right after `ViewData["Title"] = "CitiesOnMap";`, please and check. – Jackdaw Aug 18 '21 at 12:23
  • @Jackdaw nope It's not working :( but i'll search for it. Thank you so much guys sorry if i made bored or tired you – Mertcan Aug 18 '21 at 12:28
  • @Mertcan: You are welcome! Just trying to help you. The `TempData` life is very short and lies only till the target view is fully loaded. If you want to keep value in the `TempData` object after request completion, you need to call `Keep()` method. See the documentation: [TempDataDictionary.Keep](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.tempdatadictionary.keep?view=aspnet-mvc-5.2) – Jackdaw Aug 18 '21 at 12:35
  • Looks like you are using custom TagHelpers. that reference causing 500 internal server.. Can you post all the files you are referencing to the view.cshtml file. For checking purpose, you can remove '@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers' and try that it will work.. – Darga Reddy Aug 18 '21 at 12:38
  • @DargaReddy I can't post them. Stackoverflow is giving error. Is there any way to send my codes to you to review. I would really grateful. I have to continue this work for my internship – Mertcan Aug 18 '21 at 15:45
0

First you should check if TempData["cities"] is null.

if(TempData["cities"] != null)
{
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");
         }


     } 
} 

and you have to be sure about TempData["cities"] type is List<MVC.Models.City>.

umadik
  • 101
  • 2
  • 17
  • Yeah when i added "if", the exception is not thrown but i really can't understand. At top(CitiesOnMap action) I created a list of City class and I want to use it HttpPost method. How can i fix it? Because when the user select a city from dropdown and click the submit button, I want to redirect the page to the proper City view. So I have to use the class list – Mertcan Aug 18 '21 at 11:24
0

Your tempdata always null.

public IActionResult CitiesOnMap(string SelectedCity)
    {
        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;

        var res = TempData["cities"];
        foreach (var redirectedCity in TempData["cities"] as List<City>)
        {
            Console.WriteLine("bumbum");
            if (String.Equals(redirectedCity.CityName, SelectedCity))
            {
                TempData["selectedCity"] = redirectedCity;
                return RedirectToAction(redirectedCity.CityName, "City");
            }
        }
        return RedirectToAction(SelectedCity, "City"); ;
    }
karagoz
  • 135
  • 5