【问题标题】:How to access the child collection attributes using parent model in .cshtml page?如何在 .cshtml 页面中使用父模型访问子集合属性?
【发布时间】:2013-12-13 07:16:52
【问题描述】:

我正在使用 MVC4 应用程序。我已经创建了模型类及其子集合。

由于我正在使用 .cshtml 页面开发一个强类型视图,该页面将父模型类作为其模型,在 .cshtml 页面中,我不知道如何访问子集合的属性。当我说类似的话时,

@Html.TextBoxFor(model=>model.)

它只列出了父级的直接属性,我不知道如何访问这个 .cshtml 页面中的子集合属性。

我的模特:

    public partial class Parentmodel
       {
        public string FirstName;
        public string LastName;

        public ICollection<ChildEntity> ChildEntityObj { get; set; }
       }

    public class ChildEntity
       {
        public decimal PhoneNumber;
        public string Addr1;
        public string CountryNowLiving;
       }

在视图中,我使用的是 ParentModel。因此,我无法访问 .cshtml 文件中的 PhoneNumber。不仅是电话号码,而且我在 ChildEntityCollection 中有很多字段。只有名字和姓氏出现在下拉列表中。我知道我必须使用 foreach 或 for 循环,但我不确定应该如何进行。

【问题讨论】:

  • 子集合是什么意思?
  • 这样的结构,public ICollection ChildEntityObj { get;放; } 在我的父模型中。这里 ChildEntity 是具有自己属性的类。
  • 你能发布你的模型类型吗?
  • 谢谢@Yair。由于您的代码,我能够访问 childEntity 对象。这非常有用。

标签: c# asp.net-mvc-4 razor attributes


【解决方案1】:

由于您的“子”对象是 ICollection,您应该能够对其进行迭代

@foreach(var child in Model.ChildEntityObj) {
    Html.TextBoxFor(x => child.MemberNameGoesHere);
}

如果您有嵌套集合,请继续堆叠 foreach 块(无需在嵌套语句中添加 @,VS 会抱怨它,所以这不是一个真正的问题,它不会构建)。

以下方法适用于模型的任何成员(decimal 或 string)

@foreach(var child in Model.ChildEntityObj) {
    // Here you basically have an object named "child" which is one
    // of the elements of your collection, as is usual in a foreach loop

    Html.LabelFor(x => child.PhoneNumber); // While we're at it, give it a label
    Html.TextBoxFor(x => child.PhoneNumber);

    // Same for other members
}

LabelFor 将显示成员名称(在本例中为“PhoneNumber”),除非您向成员添加 DisplayNameAttribute:

using System.ComponentModel.DataAnnotations;
public class ChildEntity
{
    [Display(Name="Phone Number")]
    public decimal PhoneNumber;
}

这当然可以做得更好(通过定制的EditorTemplate 对输入实施约束,即前缀和排序),但这是最基本的实现。

【讨论】:

  • 嗨@Alex,我应该在我的 ChildCollection 的每个成员上使用这个 foreach 循环吗?还是这个 foreach 循环中的所有成员?对不起我的无知...
  • 我修改了答案以考虑实际模型结构
  • 我的意思是我所显示的已编辑。它不仅有电话号码。现在我可以将所有属性放入一个 foreach 循环或每个属性的一个 foreach 循环中吗?
  • 我重新修改了代码。一个 foreach 就足够了,child 对象按照正常的foreach 行为包含所有成员。
  • 但我无法直接访问 childEntity 对象。它是 Model.ChildEntityObj。非常感谢您的代码。它帮助很大。
【解决方案2】:

foreach 循环足以显示数据,但如果您将数据发布回控制器操作,则发布的集合值可能会出现在控制器操作中,因此您可以为此目的使用 for 循环

for(int i=0;i< Model.ChildEntityObj.count;i++)
{
  Html.TextBoxFor(x => x.ChildEntityObj[i].ChildMember);
}

希望这对您将来的目的有所帮助

【讨论】:

  • 这和使用foreach是一样的
  • @Alex 但是尝试使用 foreach 循环将数据发布到控制器操作它不起作用,但这适用于“for”循环,即 defference
  • 我一直这样做,从来没有遇到过问题。我相信一段显示此类问题的代码会成为一个很好的问题。
  • @Alex 查看这些问题stackoverflow.com/questions/15636284/… 和这个stackoverflow.com/questions/14165632/… 我也遇到了同样的问题,最后使用 for 循环解决了这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 2017-12-09
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多