Skip to main content
 首页 » 编程设计

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

2024年02月13日30think

<% 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; } 
}