C# 传递到ViewDataDictionary的模型项的类型为'*';,但此ViewDataDictionary实例需要类型为';的模型项;。。IEnumerable[*]和#x27;

C# 传递到ViewDataDictionary的模型项的类型为'*';,但此ViewDataDictionary实例需要类型为';的模型项;。。IEnumerable[*]和#x27;,c#,asp.net,asp.net-mvc,asp.net-core,model-view-controller,C#,Asp.net,Asp.net Mvc,Asp.net Core,Model View Controller,我研究并实施了类似主题的解决方案,但不幸的是,它们没有为我提供解决方案 错误消息: InvalidOperationException:传递到ViewDataDictionary的模型项的类型为“CMS.Models.Page”,但此ViewDataDictionary实例需要类型为“System.Collections.Generic.IEnumerable”“1[CMS.Models.Page]”的模型项 我正在做一个简单的cms。我的目标是在列出我的页面后对它们进行一些更改 我已经尝试修复

我研究并实施了类似主题的解决方案,但不幸的是,它们没有为我提供解决方案

错误消息:

InvalidOperationException:传递到ViewDataDictionary的模型项的类型为“CMS.Models.Page”,但此ViewDataDictionary实例需要类型为“System.Collections.Generic.IEnumerable”“1[CMS.Models.Page]”的模型项

我正在做一个简单的cms。我的目标是在列出我的页面后对它们进行一些更改

我已经尝试修复错误一段时间了,但是我无法从我应用的解决方案中得到任何结果。我的猜测是关于模型结构的数据通信问题。下面是我的代码:

家庭控制器:

    public class HomeController : Controller
{

    private readonly ApplicationDbContext _dbContext;

    public HomeController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IActionResult Index()
    {
        var page = _dbContext.Pages.FirstOrDefault(x => x.Title == "Home");
        return View(page);
    }


    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
public class AdminController : Controller
{
    private readonly ApplicationDbContext _context;

    public AdminController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Pages
    public async Task<IActionResult> Index()
    {
        return View(await _context.Pages.ToListAsync());
    }

    public async Task<IActionResult> EditPage(string title)
    {
        // SELECT * FROM Pages WHERE Title = {title}
        var page = await _context.Pages.FirstOrDefaultAsync(x => x.Title == title);

        if (page == null)
        {
            page = new Page();
            page.Title = title;

            _context.Pages.Add(page);
            _context.SaveChanges();
        }
        return View(page);
    }

    // GET: Pages/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages
            .FirstOrDefaultAsync(m => m.ID == id);
        if (page == null)
        {
            return NotFound();
        }

        return View(page);
    }

    // GET: Pages/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Pages/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Title,Content,Section")] Page page)
    {
        if (ModelState.IsValid)
        {
            _context.Add(page);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(page);
    }

    // GET: Pages/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages.FindAsync(id);
        if (page == null)
        {
            return NotFound();
        }
        return View(page);
    }

    // POST: Pages/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("ID,Title,Content,Section")] Page page)
    {
        if (id != page.ID)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(page);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PageExists(page.ID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(page);
    }

    // GET: Pages/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages
            .FirstOrDefaultAsync(m => m.ID == id);
        if (page == null)
        {
            return NotFound();
        }

        return View(page);
    }

    // POST: Pages/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var page = await _context.Pages.FindAsync(id);
        _context.Pages.Remove(page);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool PageExists(int id)
    {
        return _context.Pages.Any(e => e.ID == id);
    }
}
管理员控制器:

    public class HomeController : Controller
{

    private readonly ApplicationDbContext _dbContext;

    public HomeController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IActionResult Index()
    {
        var page = _dbContext.Pages.FirstOrDefault(x => x.Title == "Home");
        return View(page);
    }


    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
public class AdminController : Controller
{
    private readonly ApplicationDbContext _context;

    public AdminController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Pages
    public async Task<IActionResult> Index()
    {
        return View(await _context.Pages.ToListAsync());
    }

    public async Task<IActionResult> EditPage(string title)
    {
        // SELECT * FROM Pages WHERE Title = {title}
        var page = await _context.Pages.FirstOrDefaultAsync(x => x.Title == title);

        if (page == null)
        {
            page = new Page();
            page.Title = title;

            _context.Pages.Add(page);
            _context.SaveChanges();
        }
        return View(page);
    }

    // GET: Pages/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages
            .FirstOrDefaultAsync(m => m.ID == id);
        if (page == null)
        {
            return NotFound();
        }

        return View(page);
    }

    // GET: Pages/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Pages/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Title,Content,Section")] Page page)
    {
        if (ModelState.IsValid)
        {
            _context.Add(page);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(page);
    }

    // GET: Pages/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages.FindAsync(id);
        if (page == null)
        {
            return NotFound();
        }
        return View(page);
    }

    // POST: Pages/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("ID,Title,Content,Section")] Page page)
    {
        if (id != page.ID)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(page);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PageExists(page.ID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(page);
    }

    // GET: Pages/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var page = await _context.Pages
            .FirstOrDefaultAsync(m => m.ID == id);
        if (page == null)
        {
            return NotFound();
        }

        return View(page);
    }

    // POST: Pages/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var page = await _context.Pages.FindAsync(id);
        _context.Pages.Remove(page);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool PageExists(int id)
    {
        return _context.Pages.Any(e => e.ID == id);
    }
}
数据库上下文:

    public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Page> Pages { get; set; }
}
public类ApplicationDbContext:IdentityDbContext
{
公共应用程序DBContext(DbContextOptions选项)
:基本(选项)
{
}
公共数据库集页面{get;set;}
}

提前感谢您的解决方案和建议

您在EditPage中的模型是一种
IEnumerable
类型,但您可以通过EditPage操作发送
piktusCMS.Models.Page
类型模型。您只需要在查看页面中更改模型。从这个
@model IEnumerable
到这个
@model piktusCMS.Models.Page

错误非常明显。您正在将单个
CMS.Models.Page
对象传递给您的
EditPage
视图,而您的视图需要一个
IEnumerable
。错误很明显-您正在尝试将单个项传递给需要收集的视图。要么将视图更改为使用单个项目,要么从控制器返回集合。我解决了,谢谢大家。正如您在
EditPage
action中所说,我将其作为一个列表。我没有注意到
返回(第页)
。我更新为
等待context.Pages.ToListAsync()
,以供思考;回顾一下你的最后一条评论和答案所带来的变化——lbracadabra——如果你不需要,不要查询整个列表。如果不想更改视图中的
@model
,只需执行
返回视图(新[]{page})
。当您有理由偏离提供的“接受”答案时,您应该提出偏离该答案的考虑和理由(特别是如果该答案忽略了解决异常的多种方法,但将其与您的场景相关联)。改进问题和答案是一个迭代过程。这是一个很好的答案,解决了此类问题隐含的“为什么”和“如何”问题陈述。(即“为什么会发生这种异常情况?”和“我如何解决它?”)但是,“如何解决它”的方法不止一种(OP最近对其问题的评论清楚地表明了这一点),您的答案可以通过承认这一点来改进。也就是说,它不是“您只需要更改…”,而是“解决此InvalidOperationException的一种方法是更改…”。列出所有可能的解决方法可能是不可取的,但承认其他方法是不可取的。