当模型是List类型时,我们如何使用lambda?
@model List<ViewModels.MyModel>
这对EditorFor
无效@Html.EditorFor(m=>m.FirstOrDefault().Value)
如何使用EditorFor绑定模型?
答案 0 :(得分:0)
您已对其进行迭代并进行索引,因为它是集合:
@for(int i =0; i <Model.Count; i ++)
{
@Html.EditorFor(m=> Model[i].Value)
}
答案 1 :(得分:0)
以下完整示例:
您的控制器代码:
public class ModelValue
{
public int ID { get; set; }
public string Name { get; set; }
}
public class TestController : Controller
{
public ActionResult Index()
{
List<ModelValue> model = new List<ModelValue>();
for (int i = 0; i < 12; i++)
{
model.Add(new ModelValue { ID = i, Name = "Name " + i.ToString() });
}
return View(model);
}
[HttpPost]
public ActionResult Index(List<ModelValue> model)
{
return View(model);
}
}
您的观看代码:
@model List<MVCApp.Controllers.ModelValue>
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(modelitem => Model[i].ID)
@Html.EditorFor(modelitem => Model[i].Name)
<br />
}
<button type="submit">Go</button>
}