I am having an issue for posting collection. I just start learing MVC and razor. I am writing a small questionnaire application all what I am doing populate a list of question and let the user answer the question and post the answer.

I have two class in the model Questionaire and QuestionRepository the controller have two method one for fetch the question other one to get the post data, the problem i am struggling when I populate the form with textbox I am struggling to post back the collection.

Basically what i want to achive pull the list of question, population on the UI with a text box, send the the list of question with the answer to the controller for processing some logic.

I Would really appreciate if someone can help me.

public class Questionnaire
{
    public string Title {
        get;
        set;
    }
    public IList<string> Questions {
        get;
        set;
    }
    public string Answer {
        get;
        set;
    }
}

public Questionnaire GetQuestionnaire() {
    return new Questionnaire {
    Title = "Geography Questions",
      Questions = new List<string>  
       {
          "What is the capital of Cuba?",
          "What is the capital of France?",
          "What is the capital of Poland?",
          "What is the capital of Germany?"
         }
        };
    }

    public int GetCustomerAnswer() {
        return 0;
    }
}

Controller

public ActionResult Index()
{
  var q = new QuestionRepository().GetQuestionnaire();  
  return View(q);
}

[HttpPost]
public ActionResult GetAnswer(QuestionRepository q) {
   return View();
}

View

@model Question.Models.Questionnaire
<h2>Question List</h2>
@using(Html.BeginForm("GetAnswer","Home"))
{
  for(int i=0;i< Model.Questions.Count;i++)
  {
    @Html.Label("Question")
    <text>@Model.Questions[i]</text>
    @Html.TextBox(Q => Model.Questions[i])
    <br /> 
  }
  <input type="submit" name="submit" />
}

Related posts

Recent Viewed