I have a list in Razor Page which i want to use in java script.I'm using viewdata to send data to view VIewbag is working for some reason in razor page. I'm using .net core 2.2
Things i already tried.
View
Things i already tried:
- var [email protected]
- var stringArray = @Html.Raw (Json.Serialize(ViewData["Quest"]));` viewdata[Quest] contains list
- string jsonn = JsonConvert.SerializeObject(quelist);` and then send jsoon to view.
- using custom class object and create create json object using Newtonsoft.Json and send to view
If you proposing ajex solution explain it a little as i dont know much about it or share a link for explanation
Razor page .cs file Commented the things that didn't
public async Task OnGetAsync()
{
ViewData["opt1"] = o1list;
ViewData["quest"] = quelist;
// string jsonn = JsonConvert.SerializeObject(quelist);
// ViewData["Jon"] = jsonn;
QuestionBank = await _context.QuestionBank
.Include(q => q.QuestionLevel)
.Include(q => q.QuestionStyle)
.Include(q => q.Teacher)
.Include(q => q.Topic).ToListAsync();
Answer = await _context.Answer.ToListAsync();
QSID = await _context.QSID.ToListAsync();
View
@{var name = (List<String>)ViewData["Quest"]; }
<script>
/*function test() {
var array = @Html.Raw(Json.Serialize(ViewData["Jon"]));
for(var i = 0; i < array.length; i++) {
alert(array[i]);
console.log(array[i]);
}
}
test();
*/</script>
</head>
<body>
@{
Model.run();
var name = (List<String>)ViewData["Quest"];
var nam = (List<String>)ViewData["opt1"];
int j = 0;
for (int i = 0; i <= 4; i++)
{
var a = name[i];
<p > @a </p>
<form action="">
<input type="radio" name="s" value="">@nam[j]<br>
@{j = j + 1; }
<input type="radio" name="s" value="">@nam[j]<br>
@{j = j + 1; }
<input type="radio" name="s" value="">@nam[j]<br>
@{j = j + 1; }
<input type="radio" name="s" value="">@nam[j]
@{j = j + 1; }
</form>
}
}
I expect to get a array containing my list or in json format
ViewData["jon"]in your controller, but you try to access it withViewData[Jon"]in your view. The key should have the same case for it to work.