我有一个灵活的表格。这意味着根据您在下拉列表中所做的选择,字段会有所不同。此外,被调用的控制器动作也会发生变化。我试图用一个简单的例子来解决这个问题,但我找不到如何将数据提交给控制器并让控制器将其正确映射到定义的类。
澄清: 当用户创建一个只有一个选择的新问题时,这就是他们正在使用的表单/控制器。但是,当他们创建具有多个选择的问题时,我想使用相同的表单/控制器。我得到的错误是对象为空。我认为这意味着无论何时将数据传递给控制器,它都没有正确映射到对象中。如何将数据显式映射到我定义的对象中?还是我应该以不同的方式做这件事?
这是控制器:
[HttpPost]
public ActionResult CreateSimpleQuestion(SimpleQuestion question)
{
if (ModelState.IsValid)
{
question.question.is_counted = true;
question.question.DateCreated = DateTime.Now;
db.Questions.Add(question.question);
db.QuestionChoices.Add(question.choices[0]);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
这是课程:
[Serializable]
public class SimpleQuestion
{
public Question question { get; set; }
public QuestionChoices[] choices { get; set; }
}
这是调用控制器操作的脚本:
<script type="text/javascript">
$("form").on("submit", function (event) {
event.preventDefault();
var data = $('form').serialize();
console.log(data);
$.post('/Question/CreateSimpleQuestion/', data);
});
</script>
这是序列化的数据:
QuestionTitle=faketitle&Keywords=fakekeywords&Description=fakedescription&Comments=fakecomments&QuestionType=Simple&DisplayText=fakequestiontext&OrderNumber=fakeorder
如果您需要模型的细节:
public class Question
{
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public DateTime DateCreated { get; set; }
public string QuestionType { get; set; }
public string Keywords { get; set; }
public bool is_counted { get; set; }
public int? ParentId { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string Description { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string Comments { get; set; }
//These define a one to many relationship
public virtual ICollection<TeamQuestionRoster> TeamQuestionRosters { get; set; }
public virtual ICollection<Response> Responses { get; set; }
public virtual ICollection<QuestionChoices> QuestionChoices { get; set; }
}
public class QuestionChoices
{
public int QuestionChoicesId { get; set; }
public string DisplayText { get; set; }
public int OrderNumber { get; set; }
public bool is_correct { get; set; }
//These are the FK properties
public int QuestionId { get; set; }
//This defines the FK Relationships
public virtual Question Question { get; set; }
//These define a one to many relationship
public virtual ICollection<ResponseDetails> ResponsDetails { get; set; }
}