ASP.NET的MVC 4的DropDownList [英] asp .net mvc 4 dropdownlist
问题描述
我使用VS2012 MVC 4 EF。我想打一个视图,用户可以上传电影标题和类型它(actionmovie,科幻等来自一个DropDownList!),并将其存储在数据库中。
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.
型号:
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; }
}
的如果我是对的,我成功地之一的类型和电影台之间一对多的关系。的
控制器
[HttpPost]
[Authorize]
public ActionResult NewMovie(Movie movie)
{
db.Movies.Add(movie);
db.SaveChanges();
return View(movie);
}
查看
@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" />
}
我真的不知道我应该怎么做这个DROPDOWNLIST在视图中,并在最安全办法做出它的具体细节在控制器
(我觉得我应该做一个列表/从movie.typeid或Type类枚举)
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
推荐答案
我使用List我的下拉列表。要做到这样,你可以建立你的控制器上的列表这样
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;
您只能传递模型视图。从code你逝去的电影模式,使放
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; }
在您的模型。然后在视图中,可以建立你的DropDownList像这样
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.
这篇关于ASP.NET的MVC 4的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!