How to declare in the View?

S A 81 Reputation points
2022-04-01T12:31:43.653+00:00

How to declare in the View?
@{
var kvp = ViewData["kvp"] as KeyValuePair<int, string>[]>;
}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,234 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,161 Reputation points
    2022-04-01T14:28:03.343+00:00

    Your KeyValuePair syntax is incorrect so I'm not sure of the exact code. The cast syntax is either...

    @{  
        var kvp = (KeyValuePair<int, string>)ViewData["kvp"];  
    }  
    

    ...or...

    @{  
        var kvp = (KeyValuePair<int, string[]>)ViewData["kvp"];  
    }  
    

    Casting and type conversions (C# Programming Guide)


6 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,161 Reputation points
    2022-04-05T14:45:14.64+00:00

    You are using controller, but I'm using x.cshtml.cs.

    You specifically tagged this post as dotnet-aspnet-core-mvc and the reason why your getting MVC solutions.

    May be because of this I have errors???

    Unlikely. Razor Pages is like a wrapper for MVC. Your are receiving error because there are mistakes in your source code or design. This community can help you if you post source code that reproduces the exact error. Otherwise, we can only guess where the mistakes are in your code and/or design. Please post your source code.

    Working and tested Index.cshtml.cs example (Razor Pages) .NET 3.1.

        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public void OnGet()
            {
                KeyValuePair<int, string>[] values = new KeyValuePair<int, string>[]
                {
                    new KeyValuePair<int, string>(1, "Hello"),
                    new KeyValuePair<int, string>(2, "World")
                };
    
                ViewData["kvp"] = values;
            }
        }
    

    Markup

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
        var kvp = ViewData["kvp"] as KeyValuePair<int, string>[];
    }
    
    <div>
        @foreach (var item in kvp)
        {
            <div>
                @item.Key: @item.Value
            </div>
        }
    </div>
    
    0 comments No comments

  2. S A 81 Reputation points
    2022-04-07T14:31:07.613+00:00

    Thank you very much for everyone.

    0 comments No comments