c# - MVC - No Viewdata item with key of type 'IEnumerable<SelectListItem>' -


I'm new to MVC and ASP.NET and am trying to learn a bit, so I try to do something I am going to learn these and the trivial applications to boycott.

Well, I'm trying to create a dropdown box in which a list of books is shown where it will show the title of the book but book_id [primary key]

I get the error :: There is a ViewData item with the key 'book_id' type of 'IEnumerable'

Here's what I think.

& lt; P & gt; & Lt; Label = "book_id" & gt; Book: & lt; / Label & gt; See the & lt;% = Html.DropDownList ("Book_ID", (IEnumerable & lt; SelectListItem & gt;) Data ["Books"])% & gt; & Lt;% = Html Validity message ("Book_ID", "*")%> & Lt; / P & gt;

What's in my controller here

  // GET: / home / create // This form is generating I [authorized] Create Public ActionResult () {This.ViewData ["books"] = new selectList (_entities.BookSet.ToList (), "book_id", "title"); See Return (); } // // Post: / home / create // send it to {try {AcceptVerbs (HttpVerbs.Post), authorized] public ActionResult ([Bind (exclude = "PROBLEM_ID")] problem inProblem) // TODO: Add insert logic model here. User user = getUser (User.Identity.Name); If (user! = Null) {inProblem.user_id = user.user_id; } _entities.AddToProblemSet (in Problem); _entities.SaveChanges (); Return Redirect Action ("Index"); } Hold {return (see); }}  

and my books table looks like this

  book_id title publisher language isbn  

I agree I'm a small novice mistake; But I do not have any luck, any help would be to find out if any help would be great

Easy solution only ViewData element The name is similar to the drop down list:

  this.ViewData ["book_id"] = new selectList (_entities.BookSet.ToList (), "book_id", "title");  

It will automatically bind:

  <% = html.DropDownList ("book_id")%>  

You will also need to populate the vendetta ["book_id"] in the post version of the view if you want to display the scene again (as you do in the catch). [AcceptVerbs (HttpVerbs.Post), Authorized] Public ActionResult Build ([Bind (Exclude = "PROBLEM_ID"]] Problem inProblem {Try {// TODO: insert logic here Models. Add User User = getUser (User.Identity.Name); If (user! = Null) {inProblem.user_id = user.user_id; } _entities.AddToProblemSet (in Problem); _entities.SaveChanges (); Return Redirect Action ("Index"); } Hold {this.ViewData ["books"] = new SelectList (_entities.BookSet.ToList (), "book_id", "title"); See example // ViewData ["book_id"] return with example (); }}

Note:. This .ViewData ["books"] should really be done inside the grip - what's missing out there for its display


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -