0

I have string question and list of options. I can add questions to the DB easily. The problem is, that I couldn't figure out the way of adding options of answers to that question.

ApplicationDbContext

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Question> Questions { get; set; }
    public DbSet<Option> Options { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

Question.cs Model

    public class Question
{
    public int Id{ get; set; }
    public string Content { get; set; }
    public virtual List<Option> Options { get; set; }
}

Option.cs Model

public class Option
{
    public int Id { get; set; }
    public string Content { get; set; }
    public List<Option> OptionList; //Couldn't figure out how to use it yet. 
}

QuestionController (Cut out the parts which are irrelevant to my problem)

public class QuestionController : Controller
{
    private readonly ApplicationDbContext _context;

    public QuestionController(ApplicationDbContext context)
    {
        _context = context;
    }
    [HttpGet("add")]
    public IActionResult AddQuestion()
    {
        return View();
    }

    [HttpPost("add")]
    public IActionResult AddQuestion(Question model, Option option)
    {
        _context.Questions.Add(model);

        _context.Options.Add(option);
        _context.SaveChanges();
        return View(model);
    }
}

AddQuestion view

<form asp-controller="Question" asp-action="AddQuestion" method="post">
    <input type="hidden" asp-for="Id" />
    <label asp-for="Content"></label>
    <input asp-for="Content" type="text" />
    <input asp-for="OptionList" type="text" />    
    <button class="btn btn-success">Submit</button>
</form>

I want to add options and after pressing submit, It must be added with the Question in DB.

Guga Todua
  • 462
  • 2
  • 11
  • 27
  • Very unclear what your asking. Why does your `Option` class have a field `public List –  Feb 11 '18 at 11:22
  • I thought if I added OptionList, I would be able to add options to OptionList variable and then pass it to DB – Guga Todua Feb 11 '18 at 11:25
  • If your view is for creating a new `Question` and collection of `Option` associated with that question, then you need to dynamically add inputs to your view for a new `Option` (which will bind to your `public virtual List –  Feb 11 '18 at 11:28
  • And you `Option` class needs a `QuestionId` property to associate it with a `Question` (a FK) –  Feb 11 '18 at 11:30
  • public class Option { public int Id { get; set; } public string Content { get; set; } [ForeignKey(nameof(Question)] public int QuestionId {get; set;} public virtual Question Question {get; set;} } – Denis Kucherov Feb 11 '18 at 12:28

0 Answers0