结合嵌套对象的列表 [英] binding to list of nested objects

查看:91
本文介绍了结合嵌套对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我不知道如何工作结合嵌套的对象让我解释一下我的predicament:

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

下面是我的类:

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:

我的想法是做一个表格(伪code以下)

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>

//和想法是让尽可能多的字段集这些,因为我需要的联系人(即进入DeliveryContact

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

你可以从伪code见我不知道什么名字我的HTML元素,以便成功地将其绑定到一个模型。

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.

推荐答案

就像merekel建议诀窍是添加索引到html元素名称:

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

例如:

<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指标是动态的。

Ofcourse indexes are dynamic.

我从斯科特Hanselman的基本理念... <一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\"相对=nofollow>在这里

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

干杯,
吨。

这篇关于结合嵌套对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆