I'm trying to obtain list of Id values for which user checked a checkbox. Here's the model:
using System.Collections.Generic;
namespace TestWebApplication3.Models
{
public class TestViewModel
{
public IEnumerable<InnerViewModel> ModelData { get; set; }
public class InnerViewModel
{
public int Id { get; set; }
public bool Checked { get; set; }
}
}
}
Controller:
using System.Web.Mvc;
using TestWebApplication3.Models;
namespace TestWebApplication3.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var test = new TestViewModel();
test.ModelData = new[]
{
new TestViewModel.InnerViewModel {Id = 10},
new TestViewModel.InnerViewModel {Id = 20},
new TestViewModel.InnerViewModel {Id = 30},
new TestViewModel.InnerViewModel {Id = 40}
};
return View(test);
}
[HttpPost]
public string TestAction(TestViewModel model)
{
string s = "";
foreach (TestViewModel.InnerViewModel innerViewModel in model.ModelData)
{
if (innerViewModel.Checked)
s += innerViewModel.Id + " ";
}
return s;
}
}
}
And the View:
@model TestWebApplication3.Models.TestViewModel
@using (Html.BeginForm("TestAction", "Home"))
{
<ol>
@foreach (var testData in Model.ModelData)
{
<li>
@Html.HiddenFor(m => testData.Id)
@Html.CheckBoxFor(m => testData.Checked)
</li>
}
</ol>
<input type="submit"/>
}
So I'm displaying a list of InnerViewModel objects (created in Index action) as checkboxes. When user submits the form, I'd like to somehow obtain the list of Id values which are "checked" in TestAction method. But the returning model is always null.
In the application I'm making there are many more properties to the model, therefore it's important that the list of InnerViewModel objects is nested in the TestViewModel. I also don't want to use third party solution like MvcCheckBoxList, as it seems to me to be an overkill for such a simple task.
Can anyone explain to me what is missing for this to work?