Reputation: 29
Can anybody help me with the syntax (if this is doable) setting up asp-items parameter in a loop dynamically? Basically, my ViewBag has items Q1, Q2, Q3. Each of these has a selectList for a dropdown. I am looping though all the questions in Model.Questions, and for every one of these questions I need to get the select dropdown, which is stored in ViewBag. So it would be ViewBag.Q1, then ViewBag.Q2 etc. I tried constructing a string "ViewBag.@questionId", but I get an error about type (string when it's expecting a list).
I hope you can help!
@foreach (var question in Model.Questions) //For every question, generate question, and generate responses
{
<div class="form-row">
<label class="control-label col-md-4">@question.QuestionText</label>
@if (question.QuestionResponse.Count() != 0) //If count ViewData[QID] != 0, generate select dropdown, otherwise, input.
{
var questionId = "Q"+question.QuestionId.ToString();
<select class="form-control col-md-4" asp-items="ViewBag.???"><option></option></select>
}
else
{
<input class="form-control col-md-4" />
}
</div>
}
Upvotes: 1
Views: 1478
Reputation: 7190
You can try to change your code like below.
var questionId = "Q" + question.QuestionId.ToString();
<select class="form-control col-md-4" asp-items="(SelectList)ViewData[questionId]"><option></option></select>
Upvotes: 2