![](/img/trans.png)
[英]The ViewData item that has the key 'JobTitleID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'?
[英]ViewData Int32 must be of type IEnumerable in MVC
我收到似乎无法修复的错误:
“具有键'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);
}
你有
@Html.DropDownListFor(m => m.posts.Id, (SelectList)ViewBag.Id, Model.posts.Id);
但您的控制器方法未将SelectList
分配给名为Id
的ViewBag
属性,因此在视图中它为null,从而导致该异常。
返回视图之前,需要将ViewBag.Id
的值分配给SelectList
,尽管由于使用的是视图模型,所以我建议您包括一个属性public SelectList PostsList { get; set;}
public SelectList PostsList { get; set;}
在您的视图模型中,并将其分配给它,并用作
@Html.DropDownListFor(m => m.posts.Id, Model.PostsList);
旁注:您不清楚当前用法的第三个参数( Model.posts.Id
)在做什么(用于生成null
值标签选项)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.