Problem with data upload Dropdownlist

1

I am a beginner in MVC 5 and I am developing an application, I have the following problem, when I load a DropDownList it sometimes loads null, I do not know if it has to do with the flow of the code or if I need to initialize at some point the database, but I correct it and load it well, but when I close the visual or modify something in another side and reload the project it marks me by ViewData that the error does not exist and in viewBag that loads null.

I am doing a validation in the Controller that if some data is missing send me a view to capture that data in GET .

public ActionResult Configure()...

var listaCargo = new List<SelectListItem>();

foreach (var elem in mEncuesta.catCargo)
{
    listaCargo.Add(new SelectListItem
    {
        Text = elem.cargo,
        Value = elem.cveCargo.ToString()
    });
}

ViewData["cargo"] = listaCargo;

Code in ConfigureViewModel :

[Required(ErrorMessage = "Debe seleccionar un cargo")]
[Display(Name = "Seleccionar Cargo")]
public byte cveCargo { get; set; }

And in the view:

Html.DropDownList("cveCargo", (IEnumerable<SelectListItem>)ViewData["cargo"], htmlAttributes: new { @class = "form-control" })

I run it and if the session is started in cache, it runs, but if I close the project and open it again, or if I log out, I get the error:

  

System.InvalidOperationException: 'There is no ViewData element of type' IEnumerable 'with the key' cveCargo '.'

If I try it with ViewBag it marks me that the value is null.

I guess it's not a code error because I already tried several combinations and sometimes it pulls, but I do not detect where the flow error is.

    
asked by Silvia Elena Rodríguez 20.06.2017 в 21:29
source

0 answers