我正在开发一个新的问答网站。我不知道如何保存多个选项。 我不知道问题的选择方式。 我的模型是
public int QuestionID { get; set; }
public string QuestionName { get; set; }
public List<Options> Options { get; set; }
public string Answer { get; set; }
public string CreateDate { get; set; }
public bool IsDelete { get; set; }
你能帮忙如何在数据库中保存多个选项
你能帮我吗??????答案 0 :(得分:0)
我不确定“选项”究竟是什么意思,但是:
在你的问题课中有这个:
public virtual ICollection<Option> Options { get; set; } // which will be used to access your Question's options appointments.
和
public int QuestionID { get; set; } // The ID of the question that this option belong to
public virtual Question Question { get; set; } // The question that this option belong to
如果你想在问题和选项之间建立一对多的关系(“一个问题可能有很多选项,但一个选项可能只属于一个问题”)或,那么在你的Option类中
public virtual ICollection<Question> Questions { get; set; }
如果您想要多对多的关系(“一个问题可能有很多选项,一个选项可能属于许多问题”),没有链接表。
我在这里回答了类似的问题:Entity Framework Not Adding Multiple Objects In A Domain Class To Database。
对于视图,您可以使用以下内容:
@for (int i = 0; i < Model.Option.ToList().Count(); i++){
@Html.EditorFor(m => m.Option.ToList()[i]); // Create an EditorFor template for your "question" and use it here.
}
编辑:
我不太了解游览数据模型或业务逻辑,但如果您想要一个Dropdown选项,请执行以下操作: - 在控制器方法上向Viewbag添加SelectList:
ViewBag.Answer= new SelectList(question.Options, "Name_of_yuour_Option_id_field", "Name_of_a_field_that_describes_your_Option");
然后在你的观点上:
@ Html.DropDownList(“Answer”,String.Empty)
同样,我并不完全了解您的数据模型,但我相信如果您的“答案”是其中一个选项,那么您应该public string Answer { get; set; }
而不是public int AnswerID { get; set; } // where AnswerID will hold the id of the selected option.
/ p>
我希望这有助于你走得更远。还要看看有关下拉列表的stackoverflow问题(例如How to fill dropdownlist for MVC4 razor views (C#))