Reputation: 123
I'm trying to achieve something fairly simple but having some problem with the model binding.
public enum ColumnType
{
Column1 = 1,
Column2 = 2,
Column3 = 3,
Column4 = 4,
Column5 = 5,
Column6 = 6,
Column7 = 7,
Column8 = 8,
Column9 = 9
}
Further in my viewModel I have a propery of type dictionary as follows :
public class PageViewModel {
public IDictionary<ColumnType, string> Columns { get; set; }
}
Following is how my view looks like :
<tr>
<% foreach (var value in Enum.GetValues(typeof(ColumnType)))
{
%>
<%: Html.TextBox(String.Format("Columns[ColumnType.{0}]", value.ToString()))%>
<%
}
%>
</tr>
And I post above to the following POST method :
[POST]
public ActionResult Index(PageViewModel viewModel)
{
var isNull = viewModel.Columns; //The model won't bind and 'isNull' is 'null' in here
...
...
}
As you can see, the 'viewModel.Columns' property is null on the POST action.
What am I missing here?
About result, it should look like following :
// pseudocode
Columns[0] = Key=Column1, Value="text1Value";
Columns[1] = Key=Column2, Value="text2Value";
...
I know there must be something like Columns[0].Key = Column1; Column[0].Value = "text1Value"
inside the view, but I'm not sure.
Thanks a lot in advance you guys!
Upvotes: 4
Views: 1265
Reputation: 1038940
Try like this:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new PageViewModel
{
Columns = Enum.GetValues(typeof(ColumnType)).Cast<ColumnType>().ToDictionary(x => x, x => x.ToString())
};
return View(model);
}
[HttpPost]
public ActionResult Index(PageViewModel model)
{
return View();
}
}
and in the view:
<% using (Html.BeginForm()) { %>
<% for (var i = 0; i < Model.Columns.Count; i++) { %>
<%= Html.Hidden("Columns[" + i + "].Key", Model.Columns.ElementAt(i).Key) %>
<%= Html.TextBox("Columns[" + i + "].Value", Model.Columns.ElementAt(i).Value) %>
<% } %>
<input type="submit" value="OK" />
<% } %>
Upvotes: 2
Reputation: 5968
Of course it will be null
because you didn't initialize it.
You can write a constructor to the PageViewModel
which instantiate (by new
keyword) and fills the Columns with their corresponding values.
PageViewModel model = new PageViewModel();
Even though, I think you didn't explain your question enough, since the format you want to output to does not conform with what you described in the end of your question.
Upvotes: 0