当List发送给它时,它返回正确的长度但空字段
如果列表长度为5但所有字段都为空,我使用foreach迭代列表以显示它迭代的输入元素中的每个字段,例如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 };
}
答案 0 :(得分:3)
您的Person类构造函数中存在问题。你错误地设置了班级成员。这是正确的版本:
public Person(int Id,string Name)
{
Id = this.Id;
Name = this.Name;
}
而不是实际再次设置本地函数变量的版本:
{{1}}
答案 1 :(得分:3)
您的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#约定,将camel case用于方法参数,使用Pascal case用于属性。在这种情况下:
public Person(int id, string name)
{
this.Id = id;
this.Name = name;
}