I want to post a List of items to controller from Razor view , but i am getting a List of objects as null My class structre is
Model:
List
Change the action method signature to
public ActionResult OptionalMarks(ICollection
Since in your HTML, it does not look like there is anything named Id
in there. This isn't your main issue though.
Next, do the following with the foor loop
@for(int idx = 0; idx < Model[item].StudentEntires.Count();idx++)
{
@Html.TextBoxFor(_ => Model[item].StudentEntries[idx])
}
Possibly due to the use of a foreach
loop for the StudentEntries
, the model binder is having trouble piecing everything together, and thus a NULL is returned.
EDIT:
Here's an example:
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new IndexViewModel();
var subjects = new List();
var subject1 = new Subject();
subject1.Name = "History";
subject1.StudentEntires.Add(new Student { Mark = 50 });
subjects.Add(subject1);
viewModel.Subjects = subjects;
return View(viewModel);
}
[HttpPost]
public ActionResult Index(IndexViewModel viewModel)
{
return new EmptyResult();
}
}
View
@model SOWorkbench.Controllers.IndexViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
if (Model.Subjects.Any())
{
int subjectsCount = Model.Subjects.Count();
for (int item = 0; item < subjectsCount; item++)
{
@Model.Subjects[item].Name
int studentEntriesCount = Model.Subjects[item].StudentEntires.Count();
for(int idx = 0;idx < studentEntriesCount;idx++)
{
@Html.TextBoxFor(_ => Model.Subjects[item].StudentEntires[idx].Mark);
}
}
}
}
When you post the form, you should see the data come back in the viewModel
object.