Home > Enterprise >  The KeyValuePair array is not working in the View
The KeyValuePair array is not working in the View

Time:04-01

In the controller I have KeyValuePair variable:

KeyValuePair<int, string>[] kvp= new KeyValuePair<int, string>[6];
            kvp[0] = new KeyValuePair<int, string>(1, "a");
…

ViewData["kvp"] = kvp; 

In the View I cannot declare the keyValuePair:

@model IslForu.Pages.PersonalPage.DiscussionDetail

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "Hello";    
}
@{             
   var kvp = @ViewData["kvp"] as KeyValuePair<int, string>[];              
 }
… <p> kvp[i]  </p>

CodePudding user response:

I recommend to use ViewBag instead of ViewData

controller:

ViewBag.kvp = kvp;

View:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "Hello";
}

<p> @ViewBag.kvp[0]  </p>

or change yourcode to

 @{             
   var kvp = ViewData["kvp"] as KeyValuePair<int, string>[];              
 }
 <p> @kvp[0]  </p>

CodePudding user response:

you are not using @ correctly, should be


@{             
   var kvp = ViewData["kvp"] as KeyValuePair<int, string>[]; // not @ViewData["kvp"]             
 }

<p> @kvp[0].Value  </p> // not @kvp[0]

  • Related