我收到一个我似乎无法解决的错误:
“具有键'posts.Id'的ViewData项是类型的 'System.Int32'但必须是'IEnumerable'类型。“
视图模型/ PostViewModel
namespace MyBlogger.ViewModel
{
public class PostsViewModel
{
public Post posts { get; set; }
public IEnumerable<SelectListItem> Tags { get; set; }
private List<int> _selectedPostTags;
public List<int> SelectedPostTags
{
get
{
if (_selectedPostTags == null)
{
_selectedPostTags = posts.Tags.Select(m => m.Id).ToList();
}
return _selectedPostTags;
}
set { _selectedPostTags = value; }
}
}
}
PostController :(暂时手动设置ID)
public ActionResult EditPostTag(int id = 12)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var postsViewModel = new PostsViewModel
{
posts = db.Posts.Include(i => i.Tags).First(i => i.Id == id),
};
if (postsViewModel.posts == null)
return HttpNotFound();
var tagsList = db.Tags.ToList();
postsViewModel.Tags = tagsList.Select(o => new SelectListItem
{
Text = o.Name,
Value = o.Id.ToString()
});
ViewBag.UserID =
new SelectList(db.BlogUsers, "Id", "Email", postsViewModel.posts.Id);
return View(postsViewModel);
}
答案 0 :(得分:1)
你有
@Html.DropDownListFor(m => m.posts.Id, (SelectList)ViewBag.Id, Model.posts.Id);
但是您的控制器方法没有将SelectList
分配给名为ViewBag
的{{1}}属性,因此它在视图中为空,这会导致该异常。
在返回视图之前,您需要将Id
的值分配给ViewBag.Id
,但由于您使用的是视图模型,因此我建议您在属性中添加SelectList
属性查看模型并将其分配给它并将其用作
public SelectList PostsList { get; set;}
附注:您不清楚您认为当前使用情况的第3个参数(@Html.DropDownListFor(m => m.posts.Id, Model.PostsList);
)是做什么的(它用于生成Model.posts.Id
值标签选项)