Create a Table with Model in Asp. Net Core Mvc

Create a Table with Model in Asp. Net Core Mvc

I am trying to build a table in my view with values from the model. My model in the foreach loop is null. Is there something I could be missing in my controller?

My View (cshtml)

@model IEnumerable<MyApp.Models.BookModel>
@{
  ViewData["Title"] = "Index";
}

<table>
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.bookName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach(var b in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => b.bookName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => b.Author)
                </td>
            </tr>
        }
    </tbody>
</table>

Thanks!

1

1 Answer

I test the view,it's ok.So I am afraid you didn't pass the data from controller to view,or the data you passed is null.Here is a demo worked: Controller:

public ActionResult Book()
        {
            List<BookModel> list = new List<BookModel> { new BookModel { bookName = "book1", Author = "author1" }, new BookModel { bookName = "book2", Author = "author2" }, new BookModel { bookName = "book3", Author = "author3" } };
            return View(list);
        }

View:

@model IEnumerable<BookModel>
@{
    ViewData["Title"] = "Book";
}

<h1>Book</h1>

<table>
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.bookName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var b in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => b.bookName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => b.Author)
                </td>
            </tr>
        }
    </tbody>
</table>

Result:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.