c# - MVC 后模型 - 集合属性没有元素

标签 c# asp.net-mvc ado.net

<% using (Html.BeginForm("Action", "Controller", FormMethod.Post))
 {%>
<%: Html.AntiForgeryToken()%>
<%: Html.HiddenFor(m=>m.Id) %>
<% for (int i = 0; i < Model.CollectionOfItems.Count; i++)
   {%>
  <%: Html.HiddenFor(m =>Model.CollectionOfItems.ToList()[i].Id)%>
  <%: Html.HiddenFor(m =>Model.CollectionOfItems.ToList()[i].Name)%>
  <%: Html.EditorFor( m => Model.CollectionOfItems.ToList()[i].NumbersToState)%>
 <%} %>
  <input type="submit" value="submit"/>
<%} %>

问题是当我将模型发布到 Controller 操作时。 “CollectionOfItems”的计数为 0。模型状态有效且没有编译错误。

编辑 1:我收到了属性模型 - Id。 编辑 2: Controller Action

 [HttpPost]
       [ValidateAntiForgeryToken]
        public ActionResult Action(Model ReceivedModel)
        {
            try
            {
               //here i have break point to check value of ReceivedModel
              // here i can read the value id of the received model - for ex.: 5
            }
            catch (Exception)
            {
                return ""
            }
        }

编辑 3: 模型是从 ADO 实体数据模型生成的实体

public partial class Model
    {
        public Model()
        {
            this.CollectionOfItems= new HashSet<Items>();
        }
        public int Id{ get; set; }
        public virtual ICollection<Items> CollectionOfItems{ get; set; }
    }

编辑 4:

这是foreach循环的结果

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." name="[0].Id" type="hidden" value="21">

最佳答案

.ToList() 正在破坏与父对象的绑定(bind)。

这是 ViewModel 概念显示其值(value)的(许多)地方。如果您引入一个,并将其与该模型对象混合(而不是仅将数据模型用作 View 模型),您应该能够克服这个问题。

此场景的示例 ViewModel:

public class ViewModel1 // Find a better name ;)
{
    public ViewModel1 ()
    {
    }
    public int Id{ get; set; }
    public List<Items> Items{ get; set; }
}

关于c# - MVC 后模型 - 集合属性没有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050942/

相关文章:

c# - 在 where 子句中组合两个 LINQ 条件

c# - 为什么我的 Azure 网站不再可见?

asp.net-mvc - 有可能模拟/伪造扩展方法?

performance - 在嵌套列表中填充数据的最快方法

c# - TransactionScope 内的父子插入导致外键约束错误

c# - 读取excel表的问题

c# - 如何使用静态事件将信息从附加行为传递到 View 模型?

c# - 通过非默认 AppDomain 中的 C# 函数调用编码 C++ 指针接口(interface)

c# - 是否有不使用连续内存的开源 MemoryStream 实现?

asp.net-mvc - 在 ASP.Net MVC 和 ExtJS 之间序列化和反序列化日期