There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DBInstance'

StackOverflow https://stackoverflow.com/questions/22955668

  •  30-06-2023
  •  | 
  •  

Question

I have a login page with

User Name textbox Password testbox Database dropdownfor

`@Html.DropDownListFor(model => model.DBInstance, (SelectList)ViewBag.DBInstances)`

when i run my page login page is loading perfectly.with dropdown .

before keeping this dropdown .username and password validations are shown correctly . after keeping this dropdown without entering username and password ,bu default dropdown select first value

while click on submit button am getting error at dropdown that There is no ViewData item of type 'IEnumerable' that has the key 'DBInstance'.

This is my Class

[Required]
    public string UserName { get; set; }

   [Required]
   [DataType(DataType.Password)]
    public string Password { get; set; }

   public string Message { get; set; }

   public string DBInstance { get; set; } 

From Action am sending

  ViewBag.DBInstances = new SelectList(LoadDBInstances(), "Connectionstring", "InstanceName");

On submit button click i kept breakpoint at dropdownfor ViewBag.DBInstances=null ,but first time am getting values.

Was it helpful?

Solution

you need to add this line in both HttpGet and HttpPost Actions like this:

public Action Result Create()
{
ViewBag.DBInstances = new SelectList(LoadDBInstances(), "Connectionstring", "InstanceName");
return View();
}


[HttpPost]
public Action Result Create(YourModel model)
{
ViewBag.DBInstances = new SelectList(LoadDBInstances(), "Connectionstring", "InstanceName");
return View();
}

or

[HttpPost]
    public Action Result Create(FormCollection form)
    {
    ViewBag.DBInstances = new SelectList(LoadDBInstances(), "Connectionstring", "InstanceName");
    return View();
    }

Because when you set value in ViewBag it is accessible in View of that action but when another action is called the ViewBag value is destroyed and you need to set in ViewBag again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top