C# MVC post表单返回null
我正在尝试为测试创建一个动态表单。 我的问题是,当我从控制器列表中的in-post方法提交时,gq为空,但我希望用表单中填写的数据来填充。 我可以猜测它与@Html.EditorForModel()和数据绑定有关,但我不完全理解它是如何工作的。有什么想法吗?多谢各位 型号:C# MVC post表单返回null,c#,asp.net-mvc,forms,post,C#,Asp.net Mvc,Forms,Post,我正在尝试为测试创建一个动态表单。 我的问题是,当我从控制器列表中的in-post方法提交时,gq为空,但我希望用表单中填写的数据来填充。 我可以猜测它与@Html.EditorForModel()和数据绑定有关,但我不完全理解它是如何工作的。有什么想法吗?多谢各位 型号: public class GeneratedQuestions { public int GeneratedQuestionsId { get; set; } public string QuestionT
public class GeneratedQuestions
{
public int GeneratedQuestionsId { get; set; }
public string QuestionText { get; set; }
public List<StudentAnswer> QuestionAnswers { get; set; }
public int StudentTestsId { get; set; }
public virtual StudentTest StudentTests { get; set; }
}
公共类生成问题
{
public int GeneratedQuestionsId{get;set;}
公共字符串QuestionText{get;set;}
公共列表问题答案{get;set;}
public int StudentTestsId{get;set;}
公共虚拟学生测试学生测试{get;set;}
}
视图:
@model IEnumerable
@{
ViewBag.Title=“StartTest”;
}
@使用(Html.BeginForm())
{
@Html.EditorForModel()
foreach(模型中的var问题)
{
@问题,问题文本
foreach(var问题答案。问题答案)
{
@CheckBoxFor(x=>answer.WasChecked)
@DisplayFor(x=>answer.AnswerText)
@Html.HiddenFor(x=>answer.GeneratedQuestionsId)
}
}
}
控制器:
public ActionResult StartTest(int id)
{
List<GeneratedQuestions> generatedQuestions = db.StudentTests.Find(id).GeneratedQuetions.ToList();
return View(generatedQuestions);
}
[HttpPost]
public ActionResult StartTest(List<GeneratedQuestions> gq)
{
//stuff
return RedirectToAction("Index");
}
public ActionResult开始测试(int-id)
{
List generatedQuestions=db.StudentTests.Find(id.generatedQuestions.ToList();
返回视图(生成的问题);
}
[HttpPost]
公共行动结果开始测试(列表gq)
{
//东西
返回操作(“索引”);
}
如图所示:
MVC助手讨厌foreach循环。
做一个for循环,一切都会很好
编写两个循环并使用web developer工具检查它们,以查看“id”和“name”属性的差异。您需要使用
for
而不是foreach
。这只是关于可枚举模型和表单的许多其他类似问题中的一个。
public ActionResult StartTest(int id)
{
List<GeneratedQuestions> generatedQuestions = db.StudentTests.Find(id).GeneratedQuetions.ToList();
return View(generatedQuestions);
}
[HttpPost]
public ActionResult StartTest(List<GeneratedQuestions> gq)
{
//stuff
return RedirectToAction("Index");
}