我似乎在下载列表中填充和绑定MVC时遇到了一些问题。我有一个简单的例子,它有一个带有流派项目的电影列表,下面填充了一个下拉列表。
我通过一个选择列表,其中包含要填充下拉列表的项目,但在发布后期操作时似乎遇到了问题。
问题似乎是: 返回的ViewModel似乎在Post动作上将GenreList返回为null。 似乎没有设置类型,以便在编辑后 - 正确填充下拉列表。
我似乎无法找到一个好的答案,并且已经尝试了很多例子,但似乎是围成一圈。想尝试让这个最基本的下拉列表编辑示例正常工作,这样我就可以看到它应该如何实现。
模型类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class Genre
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
}
public class Movie
{
[Key]
public int MovieID { get; set; }
public string Name { get; set; }
public Genre MovieGenre { get; set; }
}
public class MovieViewModel
{
public Movie MovieItem { get; set; }
public SelectList GenreList{ get; set; }
}
}
控制器代码
namespace Test.Controllers
{
public class MoviesController : Controller
{
private DataContext _dc = new DataContext();
// GET: Movies
public ActionResult Index()
{
var x = from m in _dc.Movies
select m;
return View(x.ToList());
}
// GET: Movies/Edit/5
public ActionResult Edit(int id)
{
var x = from m in _dc.Movies
where m.MovieID == id
select m;
var l = from m in _dc.Genres
select m;
var y = new MovieViewModel
{
GenreList = new SelectList(l.ToList(), "ID", "Description"),
MovieItem = x.FirstOrDefault()
};
return View(y);
}
// POST: Movies/Edit/5
[HttpPost]
public ActionResult Edit(int id, MovieViewModel m)
{
// PROBLEM: GenreList in model is now not populate for return
if (ModelState.IsValid)
{
var movie = _dc.Movies.Find(id);
movie.Name = m.MovieItem.Name;
movie.MovieGenre = m.MovieItem.MovieGenre;
// PROBLEM: The MovieGenre does not appear to be saved correctly
// when you make the edit and go back to that record after saving
// the dropdown is not populated.
_dc.SaveChanges();
return RedirectToAction("Index", "Movies");
}
return View(m);
}
}
}
Razor查看代码
@model Test.Models.MovieViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.MovieItem.MovieID)
<div class="form-group">
@Html.LabelFor(model => model.MovieItem.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.MovieItem.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.MovieItem.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div>
@Html.LabelFor(m => m.GenreList, "Genre:")
@Html.DropDownListFor(m => m.MovieItem.MovieGenre.Id, (IEnumerable<SelectListItem>) Model.GenreList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>