0
public class Movies
{
    [Key]
    public int movieID { get; set; }

    public String Title { get; set; }

    public virtual Genres parentGenre { get; set; }
}


public class Genres
{
    public Genres()
    {
        this.movies = new HashSet<Movies>();
    }

    [Key]
    public int genreId { get; set; }

    public String genreName { get; set; }

    public ICollection<Movies> movies { get; set; }
}

通过阅读 Genres 表,我可以在我的 addmovie 视图页面上成功创建一个 DropDownList。

但是当我尝试提交页面时,它指出“值'10'无效。” 这让我相信我正在尝试将一个 Int(来自下拉列表值)放入一个对象(来自“Genres parentGenre”)。

我是否将“流派 parentGenre”与“流派 ID”外键关系正确设置为它应该只需要“父流派”字段的“数字”,还是期望更多?

添加:

控制器:

    [HttpPost]
    public ActionResult Create(Movies movies)
    {
        if (ModelState.IsValid)
        {
            db.Movies.Add(movies);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }
        IEnumerable<SelectListItem> items = db.Genres
            .Select(c => new SelectListItem
                            {
                                Value = SqlFunctions.StringConvert((double)c.genreId).Trim(),
                                Text = c.genreName
                            });
        ViewBag.genreId = items;
    }

看法:

    <div class="editor-label">
        @Html.LabelFor(model => model.parentGenre.genreName)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.parentGenre,(IEnumerable<SelectListItem>)ViewBag.genreId)
        @Html.ValidationMessageFor(model => model.parentGenre)
4

1 回答 1

1

代替您的评论,这是我的建议:

楷模:

public class Movie
    {
        [Key]
        public int MovieID { get; set; }

        public String Title { get; set; }

        public int GenreId { get; set; }

        public virtual Genre Genre { get; set; }
}

public class Genre
{
    public Genre()
    {
        this.movies = new HashSet<Movies>();
    }

    [Key]
    public int GenreId { get; set; }

    public String Name { get; set; }

    public ICollection<Movies> Movies { get; set; }
}

控制器:

[HttpPost]
public ActionResult Create(Movie Movie)
{
    if (ModelState.IsValid)
    {
        db.Movies.Add(Movie);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }
    IEnumerable<SelectListItem> items = db.Genres
        .Select(c => new SelectListItem
                        {
                            Value = SqlFunctions.StringConvert((double)c.GenreId).Trim(),
                            Text = c.Name
                        });
    ViewBag.genreId = items;
}

看法:

<div class="editor-label">
    @Html.LabelFor(model => model.Genre.Name)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Genre.Id,(IEnumerable<SelectListItem>)ViewBag.genreId)
    @Html.ValidationMessageFor(model => model.Genre)
</div>

如果我正在阅读您正确执行的操作,那应该可以。不过,我对 EF 做的不多,所以我不能 100% 确定。

于 2013-03-24T21:28:45.600 回答