binding to list of nested objects

守給你的承諾、 提交于 2019-12-11 10:15:44

问题


as I'm not sure how binding to nested objects works let me explain my predicament:

Here is my class:

public class DeliveryContactViewModel
    {        
        public List<DeliveryContact> Contacts;        
        public string Name { get; set; }
    }

    public class DeliveryContact
    {

        public string ContactType { get; set; }
        public string ContactAddress { get; set; }
        public List<bool> Reasons { get; set; }
    }

OK, so nothing extra special here...

Let's tackle View part now:

My idea was to make a form (pseudocode following)

<form action="/path/to/action" id="frm-contact" method="post">
    <input id="someID" name="Name" type="text" />
    <fieldset>
       <select name="i'm_not_sure_what_to_put_here">
           <option value="someValue1">someValue1</option>
           <option value="someValue2">someValue2</option>
       </select>
       <input id="someID" name="ContactAddress_but_i_want_it_in_the_First_DeliveryContact" type="text" />
      <input type="checkbox" value="Reason1"  name="again_not_sure"/>
      <input type="checkbox" value="Reason2"  name="again_not_sure"/>
      <input type="checkbox" value="Reason3"  name="again_not_sure"/>
  </fieldset>
</form>

//and the idea is to make as many of these fieldsets as i would need "Contacts" (that go into List of "DeliveryContact"

As you can see from the pseudocode I'm not sure what to name my HTML elements in order to successfully bind it to a model.

And finally the controller part how do I go about signing it. Will this be enough? Will the naming convention in View be enough to match everything into my controller that looks like this.

public ActionResult DeliveryContact(DeliveryContactViewModel model)
{
     foreach(var item in model.Contacts)
     {    
        //something
      }
}

Cheers, T.


回答1:


Just like merekel suggested the trick was to add indexes to html element names:

Example:

<select name="Contacts[1].ContactType">
           <option value="someValue1">someValue1</option>
           <option value="someValue2">someValue2</option>
</select>

or like this for another level of nesting

<input type="checkbox" value="true"  name="Contacts[1].Reasons[2]"/>

Ofcourse indexes are dynamic.

I got the basic idea from Scott Hanselman... Here

Cheers, T.



来源:https://stackoverflow.com/questions/14843132/binding-to-list-of-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!