1

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
  • Could you please provide more detail about the action in the controller? Commented Jul 4, 2020 at 8:12

1 Answer 1

3

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: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.