0

我的观点是强类型字典。我在 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>
 <% } %>

有人可以帮我解决这个错误吗?谢谢

4

2 回答 2

3

在视图中,使您的 html 像这种类型:

@using (Html.BeginForm("CallMe", "Call", FormMethod.Post))
{

  var list = Model as IDictionary<int, int>;

  for (var index = 0; index < Model.Count; index++)
  {
    <input type="text" name="dictionary[@index].Key" value="@list.Keys.ElementAtindex)" />
    <input type="text" name="dictionary[@index].Value" value="@list.Values.ElementAt(index)" />
  }
}

这样在控制器中你可以得到

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CallMe(IDictionary<int, int> dictionary)
    {
        // Use your dictionary

        var dictionary1 = new Dictionary<int, int>();
        dictionary1 = (Dictionary<int, int>)dictionary;
        if (ModelState.IsValid)
        {
        }
        return View(dictionary1);
    }
于 2013-10-01T08:10:01.250 回答
0

Try this

 Dictionary<object, object> dictionary = new Dictionary<object, object>();
于 2013-09-30T12:42:22.727 回答