c# - 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 值没有传递给控制器?
解决方案
测试了你的代码,它工作正常。如果您看到下面的代码段,您可以遍历所有发布的值并检查。
[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>
推荐阅读
- python - 根据所有其他列的条件计数创建新的 Pandas 列
- c# - 向量和多线程与 Unity
- reactjs - React - redux 状态更改但组件未显示更新的状态对象属性
- flutter - 无法获得不可为空的功能来处理颤振
- python - 如何在 Keras 中的 Input 和 SimpleRNN 层之间创建一对一的关系?
- c# - 需要一种解决方法来访问 ReadOnlySpan
在返回 IEnumerable 的函数内部 - java - Eclipse 方法信息创建
- sas - 将字符串中包含句点的缩写替换为 SAS 中没有句点的缩写
- spring - Spring Cloud Gateway 路由到自身
- c# - 在wpf中单击textBlock时如何更改文本块背景?