Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
2.40/5 (2 votes)
See more:
I am a fresher to ASP.net mvc and in Dropdownlist throws a InvalidOperationException while validating the form it throws a exception and i am using model validation in mvc why this error is occured plz help me soon as posssible!.... 


What I have tried:

Controller Page:

[NonAction]
        public SelectList ToSelectList(DataTable table, string valueField, string textField)
        {
            List<SelectListItem> list = new List<SelectListItem>();

            foreach (DataRow row in table.Rows)
            {
                list.Add(new SelectListItem()
                {
                    Text = row[textField].ToString(),
                    Value = row[valueField].ToString()
                });
            }
            return new SelectList(list, "Value", "Text");
        }
        public void source()
        {

            string Constr = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            OdbcConnection con = new OdbcConnection(Constr);
            con.Open();
            OdbcCommand cmd = new OdbcCommand("SELECT source_id,source_name,source_status FROM source_dets", con);
            OdbcDataAdapter da = new OdbcDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            ViewBag.source_rid = ToSelectList(dt, "source_id", "source_name");
        }
        public void industry()
        {

            string Constr = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            OdbcConnection con = new OdbcConnection(Constr);
            con.Open();
            OdbcCommand cmd = new OdbcCommand("SELECT industry_id,industry_name,industry_status FROM industry_dets", con);
            OdbcDataAdapter da = new OdbcDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            ViewBag.industry_rid = ToSelectList(dt, "industry_id", "industry_name");
        }


View Page :

@Html.DropDownListFor(a => a.source, ViewBag.source_rid as SelectList, "--Please Select--", new { @class = "form-control bg-light" })


Exception throwing:

System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'industry'.'
Posted
Updated 14-Mar-20 9:15am

1 solution

Probably you're not filling it after validation failure, see this example
There is a create Action for Vehicle first we need to send Drop down list in Get and then need to re send if ModelState is not valid

C#
public class VehicleViewModel
{
     public string VehicleName {get; set;}
     public string VehicleMake {get; set;}
     public int VehicleTypeId {get; set;}
     public List<SelectListItem> VehicleTypes {get; set;}
     
}

[HttpGet]
public ActionResult Create()
{
     var viewModel = new VehicleViewModel();

     viewModel.VehicleTypes = GetVehicleTypesSelectListItems();

     retrun View(viewModel);
}

[HttpPost]
public ActionResult Create(VehicleViewModel model)
{
    if(ModelState.IsValid)
    {
       // everything is fine save data to database
    }

    // Something went wrong for model validation so again need to refill 
    model.Vehicles = GetVehicleTypesSelectListItems();

    return View(model);
}

private List<SelectListItem> GetVehicleSelectListItems()
{
	var selectList = new List<SelectListItem>();
    var vechiles = GetAllVehicleTypes(); // get all vehicles from your db
	foreach (var element in vechiles)
	{
		selectList.Add(new SelectListItem
		{
			Value = element.Id,
			Text = element.Type
		});
	}

	return selectList;
}



Your View should be like


HTML
@Html.DropDownListFor(model => model.VehicleTypeId, Model.VehicleTypes, " --- Select --- ", new { @class = "form-control" })
 
Share this answer
 
v4
Comments
Member 14662237 16-Mar-20 1:51am    
how i want to give model for this??????how to use List<selectlistitem> GetVehicleSelectListItems for inserting value in db???????
Member 14662237 16-Mar-20 2:22am    
plzz answer the above question....
dnxit 16-Mar-20 2:27am    
Usually we show Foreign key values in a drop down
model.VehicleTypeId will give you the value selected by end user that you can store as a foreign key.
Member 14662237 16-Mar-20 2:41am    
thank you !!!!
dnxit 16-Mar-20 4:51am    
My pleasure :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900