user2831001
user2831001

Reputation: 135

Submitting Dictionary to Controller

My View is Strongly-typed Dictionary. I use Html.EditorFor() in a foreach loop that itarates over the elements in the Dictionary and creates a text fields for the values. When I try to submit the form it gives me

[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

In my Controller I have:

[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();
        }
}

Model:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master" Inherits="System.Web.Mvc.ViewPage<Dictionary<int, int>>" %>

In my View:

 <% 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>
 <% } %>

Can somebody help me with that error?? Thanks

Upvotes: 0

Views: 2573

Answers (2)

111
111

Reputation: 1779

In view, make your html like this type:

@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)" />
  }
}

So that in controller you can get

        [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);
    }

Upvotes: 3

Amit
Amit

Reputation: 15387

Try this

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

Upvotes: 0

Related Questions