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 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: