Error saving data - NullReferenceException: Object reference not set to an instance of an object

0

I'm trying to save data that pulls a list from an IEnumerable, but when saving always gives the error below. When querying the database, the data was saved correction, but always giving the exception, I already debugged and did not identify the error.

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Address_CreateOrEdit.<ExecuteAsync>b__19_0() in CreateOrEdit.cshtml, line 49

Stack Query Cookies Headers
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Address_CreateOrEdit.<ExecuteAsync>b__19_0() in CreateOrEdit.cshtml
+
                    <select class="form-control" asp-for="State" asp-items="@(new SelectList(Model.States,"Id", "State") )"></select>
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Address_CreateOrEdit.ExecuteAsync() in CreateOrEdit.cshtml
+
    Layout = "~/Views/Shared/_Layout.cshtml";
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)

This is my ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AgendaWeb.ViewsModels
{
    public class AddressViewModel
    {
        public int Id { get; set; }
        public string Number { get; set; }
        public string Complement { get; set; }
        public string Street { get; set; }
        public string Neighborhoods { get; set; }
        public string City { get; set; }
        public string State { get; set; }

        public int CityId { get; set; }

        public IEnumerable<CitiesViewModel> Cities { get; set; }

        public IEnumerable<StatesViewModel> States { get; set; }

        public IEnumerable<CountriesViewModel> Countries { get; set; }
    }

    public class CitiesViewModel
    {
        public int Id { get; set; }
        public string City { get; set; }

        public int StateId { get; set; }

    }

    public class StatesViewModel
    {
        public int Id { get; set; }
        public string State { get; set; }
        public string UF { get; set; }

        public int CountryId { get; set; }

    }

    public class CountriesViewModel
    {
        public int Id { get; set; }
        public string Country { get;  set; }
        public string Initials { get; set; }

    }

}

This My View

<div class="form-wrapper">
    <div class="col-md-12">
        <form id="form" class="form-horizontal" asp-action="CreateOrEdit" asp-controller="Address" asp-anti-forgery>
            <input type="hidden" class="form-control" asp-for="Id" />
            <div class="form-group">
                <label class="col-md-12 control-label">Endereço</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" asp-for="Street" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-12 control-label">Número</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" asp-for="Number" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-12 control-label">Complemento</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" asp-for="Complement" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-12 control-label">Bairro</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" asp-for="Neighborhoods" />
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-12 control-label">Cidade</label>
                <div class="col-md-8">
                    <select class="form-control" asp-for="CityId" asp-items="@(new SelectList(Model.Cities,"Id", "City") )"></select>

                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-8">
                    <button class="btn btn-success">Salvar</button>
                </div>
            </div>
        </form>
</div>
</div>

And this my controller

public class AddressController : Controller
    {
        private readonly AddressStorer _addressStorer;
        private readonly UserStorer _userStorer;
        private readonly CitiesStorer _citiesStorer;
        private readonly StatesStorer _statesStorer;
        private readonly CountriesStorer _countriesStorer;
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<Address> _addressRepository;
        private readonly IRepository<Cities> _citiesRepository;
        private readonly IRepository<States> _statesRepository;
        private readonly IRepository<Countries> _countriesRepository;

        public AddressController(UserStorer userStorer,
            AddressStorer addressStorer,
            CitiesStorer citiesStorer,
            StatesStorer statesStorer,
            CountriesStorer countriesStorer,            
            IRepository<User> userRepository,
            IRepository<Address> addressRepository,
            IRepository<Cities> citiesRepository,
            IRepository<States> statesRepository,
            IRepository<Countries> countriesRepository)
        {
            _addressStorer = addressStorer;
            _userStorer = userStorer;
            _citiesStorer = citiesStorer;
            _statesStorer = statesStorer;
            _countriesStorer = countriesStorer;
            _userRepository = userRepository;
            _addressRepository = addressRepository;
            _citiesRepository = citiesRepository;
            _statesRepository = statesRepository;
            _countriesRepository = countriesRepository;


        }
        // GET: Address
        public IActionResult Index()
        {
            return View();
        }

        // GET: Address/Details/5
        public IActionResult Details(int id)
        {
            return View();
        }

        // GET: Address/Create
        public IActionResult CreateOrEdit(int id)
        {

            var viewModel = new AddressViewModel();
            //var statesViewModel = new StatesViewModel();
            //var citiesViewModel = new CitiesViewModel();
            //var countriesViewModel = new CountriesViewModel();

            var states = _statesRepository.All();
            viewModel.States = states.Any()
                ? states.Select(s => new StatesViewModel { Id = s.Id, State = s.State, UF = s.UF, CountryId = s.Country.Id })
                : new List<StatesViewModel>();

            var countries = _countriesRepository.All();
            viewModel.Countries = countries.Any()
                ? countries.Select(c => new CountriesViewModel { Id = c.Id, Country = c.Country, Initials = c.Initials })
                : new List<CountriesViewModel>();


            var cities = _citiesRepository.All();
            viewModel.Cities = cities.Any()
                ? cities.Select(c => new CitiesViewModel { Id = c.Id, City = c.City, StateId = c.State.Id})
                : new List<CitiesViewModel>();


            if (id > 0)
            {
                var address = _addressRepository.GetById(id);
                var state = _statesRepository.GetById(id);
                var city = _citiesRepository.GetById(id);
                viewModel.Id = address.Id;
                viewModel.Street = address.Street;
                viewModel.Number = address.Number;
                viewModel.Complement = address.Complement;
                viewModel.Neighborhoods = address.Neighborhoods;                
                viewModel.CityId = address.City.Id;

            }

            return View(viewModel);
        }

        // POST: Address/Create
        [HttpPost]       
        public IActionResult CreateOrEdit(AddressViewModel viewModel)
        {

                // TODO: Add insert logic here
                _addressStorer.Storer(viewModel.Id, viewModel.Street, viewModel.Number, viewModel.Complement, viewModel.Neighborhoods, viewModel.CityId);

                return View();

        }
    
asked by anonymous 08.08.2018 / 03:10

1 answer

0

You're getting a NullReferenceException because when you do Post is not reloading your DropDownsList's , the code for Action CreateOrEdit on Post should look something like this:

[HttpPost]       
public IActionResult CreateOrEdit(AddressViewModel viewModel)
{
    _addressStorer.Storer(viewModel.Id, viewModel.Street, viewModel.Number, viewModel.Complement, viewModel.Neighborhoods, viewModel.CityId);

    var viewModel = new AddressViewModel();
    //var statesViewModel = new StatesViewModel();
    //var citiesViewModel = new CitiesViewModel();
    //var countriesViewModel = new CountriesViewModel();

    var states = _statesRepository.All();
    viewModel.States = states.Any()
        ? states.Select(s => new StatesViewModel { Id = s.Id, State = s.State, UF = s.UF, CountryId = s.Country.Id })
        : new List<StatesViewModel>();

    var countries = _countriesRepository.All();
    viewModel.Countries = countries.Any()
        ? countries.Select(c => new CountriesViewModel { Id = c.Id, Country = c.Country, Initials = c.Initials })
        : new List<CountriesViewModel>();


    var cities = _citiesRepository.All();
    viewModel.Cities = cities.Any()
        ? cities.Select(c => new CitiesViewModel { Id = c.Id, City = c.City, StateId = c.State.Id})
        : new List<CitiesViewModel>();

    return View(viewModel);
}
    
08.08.2018 / 04:28