I just want to bind a list of objects, display it, and post it back before adding the functionality to Add and Delete at run-time. My problem so far is that I'm not able to retrieve the list on post. Here's my code:
Models
[Serializable]
public class Animal
{
public int ID { get; set; }
public string Name { get; set; }
}
[Serializable]
public class Animals
{
public string FarmName { get; set; }
public List Farm { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var animals = new Animals();
animals.FarmName = "My Small Farm";
animals.Farm = new List();
animals.Farm.Add(new Animal() { ID = 1, Name = "Dog" });
animals.Farm.Add(new Animal() { ID = 2, Name = "Cat" });
return View(animals);
}
[HttpPost]
public ActionResult Index(Animals farm)
{
return View(farm);
}
}
View:
@using MVCTest.Models
@model MVCTest.Models.Animals
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("Index", "Home"))
{
@Html.LabelFor(x => x.FarmName)
@Html.TextBoxFor(x => x.FarmName)
for (var i = 0; i < Model.Farm.Count; i++ )
{
@Html.LabelFor(x => x.Farm[i].ID)
@Html.TextBoxFor(x => x.Farm[i].ID)
@Html.LabelFor(x => x.Farm[i].Name)
@Html.TextBoxFor(x => x.Farm[i].Name)
}
<input type="submit" value="Submit" />
}
What I have tried:
I tried using the foreach and the for loops in the View, however both of them didn't post back the initial entries. Also, I tried adding a hidden field in the for loop and named it index and set the value to the variable "i". However, this didn't work for me either.
I also tried changing List<animals> in the model Animals to IEnumerable<animals> and in the controller, I made a new POST method "public ActionResult Index(Animals animals, IEnumerable<animal> farm)". However, I still got a null for the variable "farm".
I also tried changing the LabelFor(x => x.Farm[i].ID) to HiddenFor(x => x.Farm[i].ID) however, the generate HTML looks like this: <input data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required." id="Farm_0__ID" name="Farm[0].ID" type="hidden" value="1">
I know I must be missing something, however, I'm at a loss after trying for 2 whole days. Any help and/or pointers to what I'm doing wrong would be greatly appreciated.