Reputation: 33
I'm a C programmer trying to learn C# ASP.NET MVC using Visual Studio 2015 Community Edition.
So, I have my view, and I would like to randomly show one of two 'select something' questions:
<p>I like to eat
@Html.DropDownList("answers[0]" + Model[0].ToSelectList(), "")
.
</p>
or
<p>My hair is
@Html.DropDownList("answers[1]" + Model[1].ToSelectList(), "")
.
</p>
But it turns out I can't figure out either of the requirements:
Also, I seem to be able to use this 'answers' structure without ever making it. If I end up with an 'answers' that only has data in say indexes 2, 9 and 33, does a 34 element array get passed back (Posted?)
Additional info I couldn't squeeze into comments:
@Christos I didn't want to overload the question with info, but I was thinking I would have a list of say 10 questions, but I only want each visitor to my page to answer 5. So I do the 'show one of these two questions' thing for five pairs, then I'll have my Controller do this:
[HttpPost]
public ActionResult Index(string[] answers)
{
StringBuilder sb = new StringBuilder();
foreach(var response in answers)
{
sb.Append(response);
sb.Append(",");
string responses = sb.ToString();
}
string time = DateTime.Now.ToString();
string output = time + "," + HttpResponseSubstitutionCallback;
StreamWriter sw = new StreamWriter("C:\\Temp\\responses.csv");
sw.WriteLine(output);
sw.Close();
return View();
}
When I pick up SQL I'll be able to improve this approach with databases, but for now I'm just so comfortable with CSV data it's far quicker and easier for me.
OptionModel as requested (note: I just 'borrowed' this from someone with more experience just before heading home yesterday)
public class OptionModel
{
public string SelectedOption { get; set; }
public List<string> PossibleOptions { get; set; }
public OptionModel(params string[] possibleOptions)
{
PossibleOptions = possibleOptions.ToList();
}
public IEnumerable<SelectListItem> ToSelectList()
{
return PossibleOptions.Select(x => new SelectListItem { Text = x, Value = x });
}
}
Upvotes: 3
Views: 3609
Reputation: 53958
You could try something like this:
@{
Random rnd = new Random();
// This will return either 1 or 2 randomly.
int question = rnd.Next(1, 3);
}
@if(question==1)
{
<p>I like to eat
@Html.DropDownList("answers" + Model[0].ToSelectList(), "")
</p>
}
else
{
<p>My hair is
@Html.DropDownList("answers" + Model[1].ToSelectList(), "")
</p>
}
When we make use of a block starting with the @
, @{ }
, we can place any valid c# code in this block, like to declare variables, methods etc. and later we can make use of them.
Upvotes: 4