views:

145

answers:

1

in my view I have several [n].propertyName array fields I want to turn the formCollection fields into objects myobject[n].propertyName when it goes to the controller.

so for example, the context:

View:

foreach (var item in Model.SSSubjobs.AsEnumerable())

<%: Html.Hidden("["+c+"].sssj_id", item.sssj_id )   %>
<%: Html.Hidden("["+c+"].order_id", item.order_id ) %>
<%: Html.TextBox("["+c+"].farm", item.farm %>
<%: Html.TextBox("["+c+"].field", item.field %>

c++;

Controller:

I want to take the above [0].sssj_id and turn into sssj[0].sssj_id or a list of sssj objects

My first idea was to look in the form collection for things starting with "[" but I have a feeling this isnt right...

this is as far as I got:

 public IList<SoilSamplingSubJob> extractSSSJ(FormCollection c)
        {
            IList<SoilSamplingSubJob> sssj_list=null;
            SoilSamplingSubJob sssj;


                var n=0;
                foreach (var key in c.AllKeys)   // iterate through the formcollection 
                {
                    var value = c[key];

                    if(key.StartsWith("[")) // ie turn [0].gps_pk_chx into sssj.gps_pk_chx
                       ???
                }



            return sssj_list;
        }
+1  A: 

I would let the model framework do this for you instead of writing the code yourself. From your code I cant see any reason why you would not want to do this.

Have a look at Phil Haack's post on model binding to a list.

Joel Cunningham
Thanks Joel. Tried it out and got the book program to work ok.the sequential method seemed to be nearest. when the form is submitted with [0].title, [0].author etc this goes to: public ActionResult Sequential(ICollection<Book> books) { return View(books); }but the thing is (i should have mentioned this before) I have a mix of data. some sinple form elements like name and address and others like [0].sssj_id. how can i take the [] elements out of the mix?
bergin