2013-09-30 58 views
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> 
<% } %> 

有人能帮我解决这个错误吗?由于

+1

在您看来,可以你请出示'@ model'位? –

+0

我编辑它,以便您现在可以看到:) – user2831001

+0

您是否需要说Model [key] .ToString()?我只是猜测.. – Devesh

回答

2

在视图中,像这种类型的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); 
    } 
0

试试这个

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

它不会给我一个例外,但是在CallMe()的Dictionary中,只有两个记录。首先是key =控制器,value =控制器名称。第二个是动作和动作名称。 “控制器”,“ControllerName”和“动作”,“CallMe” – user2831001

相关问题