c# - FormCollection 未传递给 Controller

标签 c# html asp.net asp.net-mvc forms

如果我直接引用 Controller 参数中的命名元素,我可以从表单中发布元素。我正在尝试使用 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">
}

使用命名参数的 Controller (beginningDate):

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

使用 FormCollection 时,它不会传递到 Controller :

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

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

最佳答案

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

[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>

关于c# - FormCollection 未传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974595/

相关文章:

asp.net - ExecuteScalar、ExecuteReader 和 ExecuteNonQuery 之间有什么区别?

c# - 如何在事件中心触发Azure函数中获取PartitionId?

c# - C# 拦截应用程序关闭

javascript - 我想单击图像的一部分来获取标题

javascript - 如何重定向 Google 协作平台上的 URL

asp.net - 将 web.config 中的子文件夹重写为子域

c# - 如何在我的在线站点中引入在线数据库

c# - 我真的应该抽象一切吗

c# - .NET 计划任务 - WqlEventQuery 每 30 分钟执行一次

javascript - 使用触摸调整 HTML 元素的大小