Asp.net core 如何使用列表列表发布表单数据?
我正在尝试保存一个列表列表,其中有一个复选框,其中包含一些选项,其中有多个选项。我得到的第一个列表很好,但是“children”道具总是返回为空 互联网上的大多数解决方案都说必须在列表中设置索引,但我没有成功地使用它 我看到有人有类似的问题: 但是我没能利用它,所以我希望你们能帮助我 视图模型Asp.net core 如何使用列表列表发布表单数据?,asp.net-core,model-view-controller,Asp.net Core,Model View Controller,我正在尝试保存一个列表列表,其中有一个复选框,其中包含一些选项,其中有多个选项。我得到的第一个列表很好,但是“children”道具总是返回为空 互联网上的大多数解决方案都说必须在列表中设置索引,但我没有成功地使用它 我看到有人有类似的问题: 但是我没能利用它,所以我希望你们能帮助我 视图模型 public class Input { public string title { get; set; } public int id { get; set;
public class Input
{
public string title { get; set; }
public int id { get; set; }
public bool value { get; set; }
public List<Input> children { get; set; }
public Input()
{
children = new List<Input>();
}
}
公共类输入
{
公共字符串标题{get;set;}
公共int id{get;set;}
公共布尔值{get;set;}
公共列表子项{get;set;}
公共投入()
{
children=新列表();
}
}
控制器
[HttpGet]
public IActionResult Services()
{
var Inputs = new List<Input>() {
new Input(){title="test",id=1 },
new Input(){title="test2",id=2,
children =new List<Input>(){
new Input(){title="test3",id=3 },
new Input(){title="test4",id=4 }
} },
};
return View(Inputs);
}
[HttpPost]
public IActionResult Services(List<Input> model)
{
return Redirect("/");
}
[HttpGet]
公共IActionResult服务()
{
变量输入=新列表(){
新输入(){title=“test”,id=1},
新输入(){title=“test2”,id=2,
children=新列表(){
新输入(){title=“test3”,id=3},
新输入(){title=“test4”,id=4}
} },
};
返回视图(输入);
}
[HttpPost]
公共IActionResult服务(列表模型)
{
返回重定向(“/”);
}
看法
@型号列表;
@for(int i=0;im[i].title)
@Html.HiddenFor(m=>m[i].id)
@Html.HiddenFor(m=>m[i].children)
@CheckBoxFor(m=>m[i].value,新的{@class=“form check-input-collapser”})
@模型[i].标题
if(模型[i]。子项!=null){
字符串containerName=“[”+i+“].值“+”Container”;
@对于(int c=0;cm[i].children[c].title)
@Html.HiddenFor(m=>m[i].children[c].id)
@Html.HiddenFor(m=>m[i].children[c].children)
@CheckBoxFor(m=>m[i].children[c].value,新的{@class=“form check input”})
@模型[i]。子对象[c]。标题
}
}
}
拯救
使用浏览器的开发工具(按F12键)检查网络中请求头的表单数据,如果模型绑定的一致性出现问题,请尝试注释掉以下代码行:
@Html.HiddenFor(m => m[i].children)
@Html.HiddenFor(m => m[i].children[c].children)
这正是问题所在!非常感谢:D
@Html.HiddenFor(m => m[i].children)
@Html.HiddenFor(m => m[i].children[c].children)