ASP.Net Core MVC Razor view rendering data from controller with dynamic casting
In my MVC application I'm using IEnumerable interface inside my repository for the database model, and using it in the controller to pass the data to view using ViewData["roles"] = _userRolesRepository.GetAll(); which is GetAll() uses IEnumerable interface here.
But when I'm trying to foreach the data on Razor view using:
@{
var users = ViewData["roles"];
}
@if (users is not null)
{
@foreach (var user in users)
{
<h3>Test User Roles Results Set</h3>
<h3>Id: @user.Id</h3>
<h3>Name: @user.Name</h3>
}
}
But then compiler throws and error - "foreach statement cannot operate on variables of type 'type1' because 'type2' does not contain a public definition for 'identifier'".
When I cast the users data to "dynamic" all good.
@{
var users = ViewData["roles"];
}
@if (users is not null)
{
@foreach (var user in (dynamic)users)
{
<h3>Test User Roles Results Set</h3>
<h3>Id: @user.Id</h3>
<h3>Name: @user.Name</h3>
}
}
I would like to know what happens here?
2 Replies
Don't use
ViewData
It's basically Dictionary<string, object>
Pass the model to the view instead
return View(theData)
Then your view with annotate @model TheTypeOfTheData
And you get full and proper type-safety@ZZZZZZZZZZZZZZZZZZZZZZZZZ - I see. Thanks for sharing this.