Kya Clark
Kya Clark

Reputation: 119

InvalidOperationException when using select query in ASP.NET Core MVC

I am creating a table that will display certain columns from my SQL database. I am getting the error

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List, but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable

I have tried running a raw sql query (using .FromSqlRaw) but that returns a null model value in my view. I understand the error and that setting my query to a list and returning an IEnumerable is not possible, but I have found no success online. Please let me know what I can improve. Thanks!

My View

@model IEnumerable<MyApp.Models.BookModel>
            <table>
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.BookName)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Author)
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.BookName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Author)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

My Controller

        [HttpGet("[action]")]
        [Route("/Books/Index")]
        public async Task<IActionResult> Index()
        {
            try
            {
                var data = _context.BookModel
                    .Where(x => x.Id == 10)
                    .Select(x => new { x.BookName, x.Author })
                    .AsNoTracking()
                    .ToListAsync();

                return View(await data);
            }
            catch (Exception)
            {

                throw;
            }
        }

Side note: setting the id = 10 for testing purposes.

Upvotes: 0

Views: 293

Answers (1)

Mohammed Sajid
Mohammed Sajid

Reputation: 4903

You could send list of MyApp.Models.BookModel, change the query to :

var data = _context.BookModel
    .Where(x => x.Id == 10)
    .Select(x => new BookModel { BookName = x.BookName, Author = x.Author })
    .AsNoTracking()
    .ToListAsync();

OR

var data = _context.BookModel
    .Where(x => x.Id == 10)
    .Select(x => new { x.BookName, x.Author })
    .AsNoTracking()
    .Select(x => new BookModel { BookName = x.BookName, Author = x.Author })
    .ToListAsync();

I hope you find this helpful.

Upvotes: 1

Related Questions