具有键“CategoryId”的 ViewData 项的类型为“System.Int32”,但必须为“IEnumerab

本文关键字:Int32 IEnumerab System CategoryId ViewData 类型 | 更新日期: 2023-09-27 18:33:37

我试图将一些新帖子保存到我的数据库中,但我反复收到错误。我在下面有一个"帖子.cs"类

    public partial class Post
    {
        public Post()
        {
            this.Replies = new HashSet<Reply>();
        }
        public int PostId { get; set; }
        public string PostTitle { get; set; }
        public string PostContent { get; set; }
        public int AuthorId { get; set; }
        public int CategoryId { get; set; }
        public System.DateTime DateCreated { get; set; }
        public virtual Category Category { get; set; }
        public virtual UserProfile UserProfile { get; set; }
        public virtual ICollection<Reply> Replies { get; set; }
    }
}

以及我用来渲染视图以供用户添加帖子的视图模型

 public class AddPostsVM
    {
        [Display(Name = "CategoryId")]
        public int CategoryId { get; set; }
        [Required()]
        [Display(Name="Title")]
        public string PostTitle { get; set; }
        [Required()]
        [Display(Name="Content")]
        public string PostContent { get; set; }
        [Required()]
        [Display(Name="Select a Category")]
        public string CategoryName { get; set; }
        public List<SelectListItem>CategoriesList { get; set; }
    }

我使用视图模型在视图中呈现带有下拉列表的视图,以获取数据库中的类别列表,以便当用户添加帖子时,他们可以选择他们希望帖子所属的类别

[HttpGet]
    public ActionResult CreatePost()
    {
        AddPostsVM model = new AddPostsVM();
        var categories = (from c in db.Categories
                         select new
                         {
                             CategoryName = c.CategoryName,
                             CategoryId = c.CategoryId
                         }).ToList();
        model.CategoriesList = categories.Select(c => new SelectListItem
        {
            Text = c.CategoryName,
            Value = c.CategoryId.ToString()
        }).ToList();

        return View(model);
    }

在我看来,CreatePost.cshtml 我有这个

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.PostTitle, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PostTitle, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PostTitle, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.PostContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.TextAreaFor(model => model.PostContent, new { htmlAttributes = new { @class = "form-control" } })*@
                <textarea class="form-control" name="PostContent" id="PostContent" rows="3"></textarea>
                @Html.ValidationMessageFor(model => model.PostContent, "", new { @class = "text-danger" })
            </div>
        </div>
                <div class="form-group">
            @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CategoryId, Model.CategoriesList, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

每当我尝试使用下面的 Post 操作将新帖子添加到数据库时

[HttpPost]
public ActionResult CreatePost(AddPostsVM model)
{
    try
    {
        if (ModelState.IsValid)
        {
            var newPost = db.Posts.Create();
            newPost.PostTitle = model.PostTitle;
            newPost.PostContent = model.PostContent;
            FormsIdentity identity = (FormsIdentity)User.Identity;
            int nUserID = Int32.Parse(identity.Ticket.UserData);
            newPost.AuthorId = nUserID;
            newPost.CategoryId = model.CategoryId;
            newPost.DateCreated = DateTime.Now;
            db.Posts.Add(newPost);
            db.SaveChanges();
            return RedirectToAction("Index", "Posts");
        }
        else
        {
            ModelState.AddModelError("", "Invalid Model");
        }
    }
    catch (DbEntityValidationException e)
    {
        foreach (var eve in e.EntityValidationErrors)
        {
            Debug.WriteLine("Entity of type '"{0}'" in state '"{1}'" has the following validation errors:",
                 eve.Entry.Entity.GetType().Name, eve.Entry.State);
            foreach (var ve in eve.ValidationErrors)
            {
                Debug.WriteLine("- Property: '"{0}'", Error: '"{1}'"",
                    ve.PropertyName, ve.ErrorMessage);
            }
        }
        throw;

    }
    return View(model);
}

我可以看到ModelState.IsValid返回false,我得到错误说

The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

请问我该如何解决这个问题?

具有键“CategoryId”的 ViewData 项的类型为“System.Int32”,但必须为“IEnumerab

ModelState 始终返回 false 的原因是属性CategoryName具有 [Required] 属性,并且您不呈现控件并回发值,因此它始终null,因此无效。但是CategoryName与选定的"与您关联的类别"下拉列表相关,因此您应该删除此属性,而仅依赖于绑定到下拉列表的CategoryId

错误的原因是,当您返回视图(由于上述问题而始终发生)时,您没有重新分配 CategoriesList 的值,因此其null@Html.DropDownListFor(model => model.CategoryId, Model.CategoriesList, ..)引发异常。

为了避免重复,你可以将公共代码重构为私有方法(注意,这假设你把public List<SelectListItem> CategoriesList { get; set; }改成public SelectList CategoriesList { get; set; }

private void ConfigureEditModel(AddPostsVM model)
{
  model.CategoriesList = new SelectList(db.Categories, "CategoryID", "CategoryName");
  // any other common stuff
}

您现在可以在 GET 方法和 POST 方法中调用

[HttpGet]
public ActionResult CreatePost()
{
    AddPostsVM model = new AddPostsVM();
    ConfigureEditModel(model);
    return View(model);
}
[HttpPost]
public ActionResult CreatePost(AddPostsVM model)
{
  if (!ModelState.IsValid)
  {
    ConfigureEditModel(model); // repopulate select list
    return View(model); // return the view to correct errors
  }
  // Save and redirect
}
相关文章: