【问题标题】:MVC post form return null [duplicate]MVC 发布表单返回 null [重复]
【发布时间】:2015-06-19 12:22:02
【问题描述】:

我正在尝试为测试制作动态表格。 我的问题是当我提交时,控制器列表 gq 中的 post 方法为空,但我希望填充表单中填写的数据。 我可以猜测它必须与@Html.EditorForModel() 和数据绑定有关,但我不完全理解它是如何工作的。任何的想法?谢谢

型号:

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; }
}

查看:

@model IEnumerable<Project.Models.GeneratedQuestions>

@{
    ViewBag.Title = "StartTest";
}

@using (Html.BeginForm())
{
   @Html.EditorForModel()

    foreach (var question in Model)
    {
        <br />
        <h1>@question.QuestionText</h1>

        foreach (var answer in question.QuestionAnswers)
        {
            @Html.CheckBoxFor(x => answer.WasChecked)
            @Html.DisplayFor(x => answer.AnswerText)
            @Html.HiddenFor(x => answer.GeneratedQuestionsId)
            <br />
        }
    }
    <input type="submit" value="Submit" />
}

控制器:

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");
}

【问题讨论】:

  • 您需要使用for 而不是foreachHere 只是关于可枚举模型和表单的许多其他类似问题之一。

标签: c# asp.net-mvc forms post


【解决方案1】:

如下所示:

ASP.NET MVC 4 - for loop posts model collection properties but foreach does not

MVC 助手讨厌 foreach 循环。 进行 for 循环,一切正常。

编写两个循环并使用 Web 开发人员工具检查它们,以查看 'id' 和 'name' 属性的差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2019-11-03
    • 2013-06-21
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多