0

I am trying to create a simple survey application and I am experiencing trouble accessing the survey's questions.

Survey Model

public class Survey
{
    public Survey()
    {
        Questions = new List<Question>();
        CompletedBy = new List<CompletedSurveys>();
    }

    public int SurveyID { get; set; }
    public string Name { get; set; }
    public List<Question> Questions { get; set; }
}

Question Model

public class Question
{
    public int QuestionID { get; set; }
    public int SurveyID { get; set; }
    public string Title { get; set; }
}

And I auto generate input fields for the questions using the code below:

<input type="hidden" name="Questions['+ itemIndex +'].QuestionID"></input>

Which renders to:

<input type="hidden" name="Questions[0].QuestionID">

What am I doing wrong? It seems like I am inserting the questions into the list incorrectly. Since my model's questions are always null.

Any guidance would be greatly appreciated.

HereToLearn
  • 292
  • 5
  • 16
  • Show us the code where you render the ``'s you mentioned – Matheus Cuba Mar 26 '18 at 21:07
  • Where are you setting the value of the input? – ElasticCode Mar 26 '18 at 21:29
  • 1
    You are not setting the `value` attribute. Always use the strongly typed `HtmlHelper` methods to generate you form controls correctly (and you will need a `for` loop of `EditorTemplate` as described in [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)) –  Mar 26 '18 at 21:39

1 Answers1

0

You don't need to JavaScript for generating hidden fields in this case. You can do it with a loop and @Html.Hidden like this:

for(int i = 0; i < Model.Questions.Count; i++)
{
    @Html.Hidden(Model.Questions[i].QuestionID.ToString())   
}
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55