1

I want to post my list of object to my controller.

This is my class file:

 public class MyModel
    {
        public int Id {get; set;}
        public List<ChildModel> ChildModelObject{ get; set; }
    }

public class ChildModel
    {
        public int ChildId {get; set;}
        public int sum {get; set;}
    }

My View Page:

 @model Demo.MyModel

      @using (Html.BeginForm())
        {
          @{ int i = 0; }
          @foreach (var item in Model.ChildModelObject) //first I am displaying value and then on submit i will post this value
           {
              <input type="hidden" name="@Html.Raw("ChildModelObject[" + i + "].ChildId")" value="@item.ChildId" /> //This is how i am taking value and it is working perfect and i am getting childid.
             @Html.DisplayFor(modelItem => item.sum)
           }
<input type="submit" value="Save"/>
        }

Controller:

 public ActionResult Index(MyModel model)//In this i want all childid when form is posted
        {
        }

So now when i click on submit button then i want all childid in my MyModel object.

Can anybody tell me any better approach then what i am doing??

8
  • 1
    You have 2 options: use for loop so you have iterator in it or use EditorTemplates Aug 12, 2015 at 10:38
  • @teovankot:Can you post your ans please and i dont want to use any extra variable and if possible use razor hidden controls Aug 12, 2015 at 10:40
  • 1
    Do not use a foreach loop - use for (int i = 0; i < Model.ChildModelObject.Count; i++) { @Html.HiddenFor(m => m.ChildModelObject[i].ChildId ) @Html.DisplayFor(m => m.ChildModelObject[i].sum) }
    – user3559349
    Aug 12, 2015 at 10:40
  • @StephenMuecke:Thanks Aug 12, 2015 at 10:41
  • 1
    But what is the point of this - all your doing is sending extra data acroos to the client and then sending exactly the same back to the server (and in the process opening yourself up to overposting attacks and degrading erformance). Just get the collection again in the POST method if you need it for some reason
    – user3559349
    Aug 12, 2015 at 10:42

1 Answer 1

1

You should create Editor Template for your ChildModel class like this:

@model Demo.ChildModel

@Html.HiddenFor(x => x.ChildId)
@Html.DisplayFor(x => x.sum)

Place it in Views/Shared/EditorTemplates folder (or in your controller EditorTemplates) and name it ChildModel.cshtml

And then you can use it like this:

@model Demo.MyModel

@using (Html.BeginForm())
{
   @Html.EditorFor(x=>x.ChildModelObject)
   <input type="submit" value="Save"/>
}

Note that you don't need any loops MVC generate right bindings itself

1
  • 2
    You should make it clear the the template needs to be named ChildModel.cshtml
    – user3559349
    Aug 12, 2015 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.