Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C#
[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:
C#
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:
C#
@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.
Posted
Updated 11-Dec-18 2:01am
v2

 
Share this answer
 
@using (Html.BeginForm("Index", "Home"))
{
    @Html.LabelFor(farm => farm.FarmName)
    @Html.TextBox("farm.FarmName", Model.FarmName)

    for (var i = 0; i < Model.Farm.Count; i++)
    {
        @Html.LabelFor(x => x.Farm[i].ID)
        @Html.TextBox(string.Format("farm.Farm[{0}].ID", i), Model.Farm[i].ID)

        @Html.LabelFor(x => x.Farm[i].Name)
        @Html.TextBox(string.Format("farm.Farm[{0}].Name", i), Model.Farm[i].Name)
    }
    
    <input type="submit" value="Submit" />
}


You can look at custom binding also

http://www.prideparrot.com/blog/archive/2012/6/customizing_property_binding_through_attributes[^]

There might be a better way of doing this than the above, so see if you get other answers.
 
Share this answer
 
Comments
Ryan Zahra 22-Feb-16 6:06am    
Thanks! This looks like to be my solution as I tried it out and it worked for me. Could you explain to me why you had to change TextBoxFor to TextBox for the FarmName? In my original code it was working, however, in your solution, I had to change it like yours in order to have the farmName posted back. Thanks a lot for your help!
F-ES Sitecore 22-Feb-16 6:12am    
It was so I could create the relevant names myself rather than using the ones the TextBoxFor give you. The default model binding and helpers works for complex objects (ie objects with properties) and also lists of objects, but the helpers can't generate the right names for lists that are properties on other objects.
Ryan Zahra 22-Feb-16 6:15am    
Thanks for clarifying!
public JsonResult OppDetails(int Id)
       {
           var data = _crmNewCustomerService.GetOppById(Id).Data;
           var selected = data.ToList();
           List<OpportunityViewModel> opportunityData = new List<OpportunityViewModel>();
           foreach (var item in selected)
           {
               if (item.OpportunityTitle != null)
               {
                   OpportunityViewModel model = new OpportunityViewModel();
                   model.CustomerId = Convert.ToInt32(item.CustomerId);
                   model.OpportunityTitle = item.OpportunityTitle;
                   opportunityData.Add(model);
               }
               else
               {

               }
           }

           return Json(opportunityData , JsonRequestBehavior.AllowGet);


       }
 
Share this answer
 
Comments
Richard Deeming 21-Dec-18 10:54am    
Absolutely nothing to do with the (already-solved) question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900