asp .net mvc 4 dropdownlist
asp.net, asp.net-mvc-4, drop-down-menu, entity-framework
Solution
I use List for my dropdown list. to do it that way you can build the list like this on your controller
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in Movies){
ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}
Movie.MovieList = ls;
you can only pass one model to the view. from your code you are passing the movie model so put
public List<SelectListItem> MovieList { get; set; }
in your model. Then on the view you can build your dropdownlist like this
@Html.DropDownListFor(x => x.Id, Model.MovieList)
Let me know if you have any questions.
Problem
I am using VS2012 MVC 4 with EF. I want to make a view where the user can upload movie title and type for it (actionmovie, scifi, etc that comes from a dropdownlist!), and store it in database. Model: ``` public class Movie { [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } [ForeignKey("Type")] public int TypeId { get; set; } public virtual Type Type { get; set; } } public class Type { [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int TypeId { get; set; } public string TypeName { get; set; } public virtual ICollection<Movie> Movies { get; set; } } ``` If I am right I successfully made One to Many relationship between the Type and Movie table. Controller: ``` [HttpPost] [Authorize] public ActionResult NewMovie(Movie movie) { db.Movies.Add(movie); db.SaveChanges(); return View(movie); } ``` View: ``` @using (Html.BeginForm()) { <table> <tr> <td>@Html.DisplayNameFor(model => model.Name)</td> <td>@Html.DisplayNameFor(model => model.TypeId)</td> </tr> <tr> <td>@Html.TextBoxFor(model => model.Name)</td> <td>@Html.DropDownListFor......... </tr> </table> <input type="submit" value="submit" /> } ``` I do not really know how should I make this Dropdownlist in the view, and make the specific details for it in the controller with the most secure way (I think i should make a list/enumerable from the movie.typeid or the Type class) I would be very glad if you could help me! Thank you