Reputation: 12695
I have that error
The ViewData item that has the key 'BookAttributesDDL' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.
in that code:
@Html.DropDownList("BookAttributesDDL", Model.BookAttributes_Items)
but the Model.BookAttributes_Items
is type of the IEnumerable<SelectListItem>
! What's wrong ?
The ViewData.Keys
property from the Immediate Window:
ViewData.Keys
Count = 2
[0]: "FCoookie"
[1]: "Title"
Upvotes: 0
Views: 881
Reputation: 4732
Fully agree with View Model approach response to you (and its me who selected it as useful). However, if you don't want to switch, but remain as is I bet your answer lays in this article.
Hope this help you.
Upvotes: 0
Reputation: 218702
Try to avoid dynamic variables like ViewBag and ViewData. It will make your code unreadable and painful to maintain in future as it grows. ViewBag is like Magic strings !
Switch to the ViewModel approach.
Example, If you are creating a View to Create a Book, Create a Viewmodel
(it is just a plain Class) for that like this
public class BookViewModel
{
public int BookId { set;get;}
public string BookName {set;get;}
public IEnumerable<SelectListItem> Attributes{ get; set; }
public int SelectedAttribute{ get; set; }
}
Now in your GET
Action, Simply create an object of this class, Set the BookAttribbutes
proeprties to your Dropdown items and pass this ViewModel object to the View
public ActionResult Create()
{
BookViewModel vm=new BookViewModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Attributes=new[]
{
new SelectListItem { Value = "1", Text = "F Cookie" },
new SelectListItem { Value = "2", Text = "Title" },
}
return View(vm);
}
Now in We will make our view strongly typed to this ViewModel class
@model BookViewModel
@using(Html.BeginForm())
{
@Html.TextBoxFor(x=>x.BookName)
@Html.DropDownListFor(x => x.SelectedAttribute,
new SelectList(Model.Attributes, "Value", "Text"), "Select Attribute")
<input type="submit" value="Save" />
}
Now you will get the Selected Dropdown value and the textbox value in your HttpPost action by accessing the corresponding properties of your ViewModel
[HttpPost]
public ActionResult Create(BookViewModel model)
{
if(ModelState.IsValid)
{
//check for model.BookName / model.SelectedAttribute
}
//validation failed.TO DO : reload dropdown here
return View(model);
}
Upvotes: 1