【问题标题】:Why When List sent to view it return correct length but all fields are empty?为什么发送列表以查看它返回正确的长度但所有字段都是空的?
【发布时间】:2018-04-06 15:57:56
【问题描述】:

当发送列表以查看它时返回正确的长度但为空字段

我使用 foreach 遍历列表以显示输入元素中的每个字段,例如,如果列表长度为 5 但所有字段为空,则它会迭代 5 次

查看

@model.myProject.TwoModels 
@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
    @foreach (var tuple in Model.personList )
    {       
            @Html.EditorFor(model => @tuple.Name)                 
    }

我的模型

public partial class Person
{
        // set and get to id and name
        public Person(int Id,string Name)
        {
            Id = this.Id;
            Name = this.Name;
        }
}

public class A
{
   private List<Person> personList { get; set; }

   public List<Person> PersonList
   {
        get
        {
            return personList;
        }
        set
        {
            personList= value;
        }
    }
}

public class B
{
    public void method(B b)
    {
        b.PersonList = new List<Person>();

        //it's just example
        for (int i=0;i<5;i++)
        {
            b.PersonList.Add(new Person(1,"Ali")));
        }
    }
}

我用这个模型来组合拖曳模型

namespace myproject.Models
{
    public class TwoModels
    {
        // example is another model
        public example firstModel { get; set; }
        public List<Person> personList { get; set; }
    }
}

控制器

public List<Person> method()
{
    A a =new A();
    B b =new B();

    //other code //
    return b.PersonList;
}

public ActionResult Edit(int id)
{
    List <Person> list = method();
    example ex=database.example.Find(id);

    var TwoModels = new TwoModels { firstModel = ex, personList = list };
}

【问题讨论】:

  • 看起来您需要调用B.method(b) 才能创建列表并填充它。也许而不是B类中的method应该是构造函数的逻辑?
  • 您可能还想阅读Post an HTML Table to ADO.NET DataTable,因为当您提交表单时没有任何效果
  • @Stephen Muecke 我知道这只是示例而不是完整的代码,因为我有一个提交按钮
  • 这与没有提交按钮无关 - 请阅读 - 你不能使用 foreach 循环来生成表单控件!

标签: c# asp.net-mvc


【解决方案1】:

您的 Person 构造函数是倒退的。而不是这个,它将每个属性的(null)值分配给本地参数:

public Person(int Id,string Name)
{
    Id = this.Id;
    Name = this.Name;
}

您需要将参数的值分配给属性:

public Person(int Id,string Name)
{
    this.Id = Id;
    this.Name = Name;
}

为避免将来出现这种混淆,您还应该考虑采用标准 C# 约定,即方法参数使用驼峰式大小写,属性使用 Pascal 大小写。在这种情况下:

public Person(int id, string name)
{
    this.Id = id;
    this.Name = name;
}

【讨论】:

    【解决方案2】:

    您的 Person 类构造函数有问题。您错误地设置了班级成员。这是正确的版本:

    public Person(int Id,string Name)
            {
                this.Id = Id;
                this.Name = Name;  
            }
    

    而不是您的版本,它实际上是再次设置局部函数变量:

    public Person(int Id,string Name)
            {
                Id = this.Id;
                Name = this.Name;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2017-08-02
      • 2020-03-08
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多