The ViewData item that has the key 'Conf_Type' is of type

Posted by Madhav1406 under ASP.NET MVC on 3/2/2017 | Points: 10 | Views : 465 | Status : [Member] | Replies : 1
When I am applying server side validation, I am getting error in dropdown

The ViewData item that has the key 'Conf_Type' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

Model :
public int Conf_Type { get; set; }


View:
@if (ViewBag.Action == "Edit")                          
{
@Html.DropDownList("Conf_Type", ViewBag.Assets_Type as SelectList, new { @class = "form-control" })
}
else
{
@Html.DropDownList("Conf_Type", ViewBag.Assets_Type as SelectList, "Select Type", new { required = "required", validationmessage = "Please select Type", selected = @Model.Assets_Type, @class = "form-control" })
}

Controller:
public ActionResult Index(int? id)   
{
VarsityContext VarsityDB = new VarsityContext();
Varsity.Models.Configuration configuration = new Varsity.Models.Configuration();
try
{
TempData["Asset Inventory"] = "Asset Inventory";
if (id != null)
{
configuration = VarsityDB.Configurations.Single(a => a.Conf_ID == id);
ViewBag.Action = "Edit";
}
else
{
ViewBag.Action = "Create";
}
IEnumerable<SelectListItem> basetypes = new SelectList(cwConfiguration.getConfigurationTypes(), "Id", "Name", configuration.Conf_Type);
ViewBag.Conf_Type = basetypes;
}
catch (Exception ex)
{ }
return View(configuration);
}





Responses

Posted by: A2H on: 3/2/2017 [Member] [MVP] Silver | Points: 25

Up
0
Down
one common reason for this exception is the ViewBag.Assets_Type will be null. Double check and ensure that you have values in Viewbag.

Another reason is If your ModelState is not valid on your POST action, you need to repopulate your SelectList properties. You can check the below link for more details.
http://stackoverflow.com/questions/3393521/the-viewdata-item-that-has-the-key-my-key-is-of-type-system-string-but-must

Thanks,
A2H
My Blog

Madhav1406, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response