我想创建一个create-view,您可以在其中为多个实体输入值- "a list of entity“,例如Entity Class
public class MyEntity{
public string myAttribute { get; set; }
}对于视图,我创建了一个如下所示的ModelView:
public class MoreEntites{
public List<MyEntity> MyEntities { get; set; }
}在视图中,我想使用MoreEntities让用户可以在一个视图中输入多个数据集(我的建议当然不起作用)
@model myproject.ViewModels.MoreEntities
...
<div class="editor-label">
@Html.LabelFor(model => model.MyEntities.ElementAt(0).MyAttribute)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MyEntities.ElementAt(0).MyAttribute)
@Html.ValidationMessageFor(model => model.MyEntities.ElementAt(0).MyAttribute)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MyEntities.ElementAt(1).MyAttribute)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MyEntities.ElementAt(1).MyAttribute)
@Html.ValidationMessageFor(model => model.MyEntities.ElementAt(1).MyAttribute)
</div>
...现在,在控制器中,我希望遍历列表,并将MyEntities的每一项写入数据库。当我运行程序时,我得到一个异常,我的列表是null,我应该在使用它之前检查它是否为null。这是可能的吗?它是如何工作的?一种“解决方案”是创建一个数组,但在这种情况下,我的程序是可伸缩的。感谢您的帮助!
发布于 2013-11-26 20:38:31
使用实体的Array[]!解决方案:型号:
public class MyEntity{
public string MyAttribute { get; set; }
}ViewModel:
public class MoreEntites{
public MyEntity[] MyEntities { get; set; }
}查看:
@model myproject.ViewModels.MoreEntities
...
<div class="editor-label">
@Html.LabelFor(model => model.MyEntities[0].MyAttribute)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MyEntities.[0].MyAttribute)
@Html.ValidationMessageFor(model => model.MyEntities[0].MyAttribute)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MyEntities[1].MyAttribute)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MyEntities[1].MyAttribute)
@Html.ValidationMessageFor(model => model.MyEntities[1].MyAttribute)
</div>
...控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMoreEntitiesAtOnce(MoreEntities set)
{
foreach(var item in set.MyEntities)
{
db.MyEntity.Add(item);
}
db.SaveChanges();
return RedirectToAction("Index");
}在我的例子中,如果必须尝试,如果可以通过JavaScript向视图添加更多的TextBoxes,因此在将它们添加到DOM时,您需要在普通html中递增文本框的名称
https://stackoverflow.com/questions/20205295
复制相似问题