如果我直接引用 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/