我有一个像这样的模型
public class Model
{
public int Value { get; set; }
public List<OtherModel> List { get; set; }
}
public class OtherModel
{
public int Value1 { get; set; }
public int Value2 { get; set; }
public bool IsPropTrue { get; set; }
}
我在 View 中使用 Model
,在其中循环遍历 List
以在表格中显示数据。
根据 OtherModel
中的属性之一 (IsPropTrue
) 是真还是假,我想使用 HiddenFor
Html 帮助程序和将数据发送到 HttpPost
Controller 。
@model Model
@foreach (var item in Model.List)
{
if (item.IsPropTrue)
{
@Html.HiddenFor(model=> item.Value1)
@Html.HiddenFor(model=> item.Value2)
}
}
我认为它不起作用,因为我应该以某种方式将这些属性添加到 Model
中的 OtherModel
;但我现在拥有它的方式是向 Model
添加属性。
最佳答案
你可以这样做:
@model Model
@foreach (var item in Model.List)
{
if (item.IsPropTrue)
{
@Html.HiddenFor(model => model.List[Model.List.IndexOf(item)].Value1)
@Html.HiddenFor(model => model.List[Model.List.IndexOf(item)].Value2)
}
}
这样绑定(bind)系统会将隐藏字段与模型中的 List OtherModel 绑定(bind)
关于c# - 使用 Html helper HiddenFor C# MVC 将模型添加到模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046162/