我的观点是强类型字典。我在 foreach 循环中使用 Html.EditorFor() 遍历 Dictionary 中的元素并为值创建一个文本字段。当我尝试提交它给我的表格时
[InvalidCastException: Specified cast is not valid.]
System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +95
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
在我的控制器中,我有:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendDictionary()
{
if (ModelState.IsValid )
{
Dictionary<int, int> dictionary = new Dictionary<int, int>();
dictionary.Add(1, 1);
dictionary.Add(2, 1);
dictionary.Add(3, 1);
dictionary.Add(4, 1);
dictionary.Add(5, 1);
return View(dictionary);
}
else
{
return View();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CallMe(Dictionary<int, int> Dict)
{
if (ModelState.IsValid)
{
return View("YEs");
}
else
{
return View();
}
}
模型:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master" Inherits="System.Web.Mvc.ViewPage<Dictionary<int, int>>" %>
在我看来:
<% using (Html.BeginForm("CallMe", "Call", FormMethod.Post))
{%>
<%: Html.AntiForgeryToken()%>
<%foreach (var key in Model.Keys)
{%>
<tr>
<td>
<%: Html.EditorFor(m => Model[key])%></td>
</tr>
<% } %>
<tr>
<td>
<input type="submit" value="submit" /></td>
</tr>
<% } %>
有人可以帮我解决这个错误吗?谢谢