C
C#7mo ago
Odd_Dev_404

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
Angius
Angius7mo ago
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
Odd_Dev_404
Odd_Dev_4047mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ - I see. Thanks for sharing this.
Want results from more Discord servers?
Add your server
More Posts
"ExtensionlessUrlHandler-Integrated-4.0"I've been struggling with getting my local IIS on Win 11 to host some older (4.5.1) MVC applicationsASP .NET 7 - Testing a JWT Token GeneratorI have an ASP .NET web api which calls a CreateToken() method inside a TokenService to generate a JWCount the number of sequences of characters "cd" in a line and delete those before itletter 'b' (reHow to do it in c#... I would be very grateful if anyone could help with a sample codeInconsistent accessibility: property type 'Exercises.Register.Gender' is less accessible than properI honestly have no clue how it's having issues with accessibility when both classes are within the scookie clicker storeHello i am here ones again asking for help. My store buttons need to be dissabled if i don't have teWhere to change working directory in VS2022?How do you change the working directory for a project in Visual Studio? The project I'm working on Can you store a unique function within a class?I'm new to working with classes in C# and would like to be able to use them for a game I'm working oCan I add elements to an array while running the code?Hi there! Bashing my head in with my beginner C# assignment. From the instructions they want us to ✅ How to access internal directories in nuget package?Hello! I wanted to access internal folders of Nuget Package Dragablz and tried this way, but it didnError with getting pixelsI have tried to create some code to get the pixels of an uploaded image but the function doesn't see