首页 > 解决方案 > FormCollection 未传递给控制器

问题描述

如果我直接引用控制器参数中的命名元素,我可以从我的表单中发布元素。我正在尝试使用 FormCollection,因此我不必在后 ActionResult 参数中键入表单中的每个元素。

HTML 表单:

@using (Html.BeginForm("legallabels", "Reports", FormMethod.Post, new { id = "reportForm", @class = "report-form col-9" }))
{
    <div class="col-12">
        <b>Beginning </b><input type="text" class="form-control col-2" id="beginningDatePicker" name="beginningDate" value="@DateTime.Today.Date.ToString("MM/dd/yyyy")" />
    </div>
    <input type="submit" value="submit">
}

控制器使用命名参数(beginningDate):

[HttpPost]
public ActionResult LegalLabels(string beginningDate)
{
    return View();
}

使用 FormCollection 时,它不会传递给控制器​​:

[HttpPost]
public ActionResult LegalLabels(FormCollection form)
{
    return View();
}

在控制器中使用断点,我可以看到表单正在正确发布,并且在参数中命名表单元素(beginningDate)时一切正常。我查看了使用 FormCollection 的类似代码示例,它们似乎工作正常。为什么我的 FormCollection 值没有传递给控制器​​?

标签: c#htmlasp.netasp.net-mvcforms

解决方案


测试了你的代码,它工作正常。如果您看到下面的代码段,您可以遍历所有发布的值并检查。

[HttpPost]
public ActionResult LegalLabels(FormCollection form)
{
    StringBuilder sb = new StringBuilder();

    foreach (var key in form.AllKeys)
    {
        sb.AppendLine(string.Format("Key: {0}. Value: {1}.<br>", key, form[key]));
    }

    ViewBag.FormData = sb.ToString();

    return View();
}

在 cshtml 上

<div>
    @Html.Raw(ViewBag.FormData)
</div>

推荐阅读