I have a dictionary being used. And when the “submit” is hit, how do I also pass the dictionary with the values in it to the [HttpPost] controller method?
Currently in the [HttpPost] method, the DummyDictionary is empty, how would I fix this?
Thanks!
MODEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DummyMVC.Objects;
namespace DummyMVC.Models
{
public class TheModel
{
public TheObject Obj { get; set; }
public Dictionary<string, TheObject> DummyDictionary { get; set; }
}
}
CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DummyMVC.Models;
using DummyMVC.Objects;
namespace DummyMVC.Controllers
{
public class DummyController : Controller
{
//
// GET: /Dummy/
[HttpGet]
public ActionResult Index()
{
TheModel m = new TheModel();
m.Obj = new Objects.TheObject();
TheObject a_obj = new TheObject();
a_obj.Name = "Joe";
m.DummyDictionary = new Dictionary<string, Objects.TheObject>();
m.DummyDictionary.Add("VT", a_obj);
return View(m);
}
[HttpPost]
public ActionResult Index(TheModel model)
{
// HERE THE DICTIONARY is EMPTY, where all the form values should exist.
string test = "";
return View(model);
}
}
}
VIEW
@model DummyMVC.Models.TheModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.DummyDictionary);
@Html.LabelFor(m => m.DummyDictionary["VT"].Name)
@Html.TextBoxFor(m => m.DummyDictionary["VT"].Value)<br />
@Html.TextBoxFor(m => m.DummyDictionary["VT"].Token, new { @Value = Model.DummyDictionary["VT"].Token, style = "display:none;" })
<input type="submit" class="submit_button" /><br />
}
In the view I am using @Html.HiddenFor(m => m.DummyDictionary) to try to pass the dictionary over to the post method, but the dictionary is just empty. Without this @Html.HiddenFor the Dictionary in the post method is null.
Thank you so much for the assistance I appreciate it!
UPDATE
TheObject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DummyMVC.Objects
{
public class TheObject
{
public string Name { get; set; }
public string Value { get; set; }
public string Token { get; set; }
}
}
It’s not pretty but it works. Remember to include all properties of TheObject, if not visible then hidden so they get posted. Would probably be a good idea to make a helper for this.
Controller