I am trying to send an array from my view to the controller to save it in the database.
The user will select couple check boxes and each one should be saved int its own row.
However,nothing is sending correctly and I get this message.
System.NullReferenceException: Object reference not set to an instance of an object.
I have a very simple table that has the following:
public class Answer
{
public int Id { get; set; }
public int OptionID { get; set; }
public int QuestionID { get; set; } = 1;
}
In the view I have list of check boxes in the form that has values like this:
<input type="checkbox" name="OptionID[0]" value="1" class="single-checkbox"> checkbox 1<br>
<input type="checkbox" name="OptionID[1]" value="2" class="single-checkbox"> checkbox 2<br>
<input type="checkbox" name="OptionID[2]" value="3" class="single-checkbox"> checkbox 3<br>
<input type="checkbox" name="OptionID[3]" value="4" class="single-checkbox"> checkbox 4<br>
In my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(List<Answer> answers)
{
if (ModelState.IsValid)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
foreach (var i in answers)
{
db.Answers.Add(i);
}
await db.SaveChangesAsync();
}
return RedirectToAction("Index");
}
return View(answers);
}