将字典提交给控制器

时间:2013-09-30 11:40:19

标签: c# asp.net asp.net-mvc asp.net-mvc-4

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

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

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分:0)

试试这个

 Dictionary<object, object> dictionary = new Dictionary<object, object>();