我有字符串问题和选项列表。 我可以轻松地向DB添加问题。问题是,我无法找出添加该问题答案选项的方法。
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(删除与我的问题无关的部分)
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视图
<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>
我想添加选项,按提交后,必须将其添加到DB中的问题。