C# ASP.NET MVC 5如何编辑父级和列表<&燃气轮机;在同一视图中键入Child
我需要在同一视图中编辑列表类型的类及其子类,但我不知道如何使子类在同一视图中编辑 假设我有这些课程:C# ASP.NET MVC 5如何编辑父级和列表<&燃气轮机;在同一视图中键入Child,c#,asp.net-mvc,view,insert,C#,Asp.net Mvc,View,Insert,我需要在同一视图中编辑列表类型的类及其子类,但我不知道如何使子类在同一视图中编辑 假设我有这些课程: public class Parent { public int PValue1 { get; set; } public int PValue2 { get; set; } public int PValue3 { get; set; } public virtual List<ChildItem> Childs { get; set; } }
public class Parent
{
public int PValue1 { get; set; }
public int PValue2 { get; set; }
public int PValue3 { get; set; }
public virtual List<ChildItem> Childs { get; set; }
}
public class ChildItem
{
public int CValue1 { get; set; }
public int CValue2 { get; set; }
}
然后在PartialView中创建另一个表单来使用Insert(ChildItem child)
控制器,但我也无法实现这一点。我不知道如何将第二个表单添加到模型中,因为它是一个列表
现在这可能很明显,但我对ASP.NETMVC还不熟悉,也习惯了旧的WebForms,所以我仍然需要了解一些东西
我的目标是实现如下工作视图:
好的,通过进一步研究,我发现我不需要部分视图中的嵌套表单,而是需要具有多个表单操作的多个提交按钮。 我得到了我所需要的,显然这是非常基本的,所以我想我可以发布我自己的问题解决方案,也许可以帮助其他人解决同样的问题。 因此,从视图开始,我将其替换为:
@* WHAT TODO? *@
为此:
<label>Child Value 1</label>
<input type="number" name="CValue1" />
<label>Child Value 2</label>
<input type="number" name="CValue1" />
<!--This is the real trick! -->
<input type="submit" formaction="AddChild" formmethod="post" />
为此:
@for(int x = 0; x < Model.Childs.Count; x++){
<tr>
<td>@Html.DisplayFor(m => m.Childs[x].CValue1)</td>
<td>@Html.DisplayFor(m => m.Childs[x].CValue2)</td>
<td> <button type="submit" formaction="DeleteChild" name="ChildID" value="@Model.Childs[x].ID" formmethod="post">X</button>
@Html.HiddenFor(m => m.Childs[x].ID)
@Html.HiddenFor(m => m.Childs[x].CValue1)
@Html.HiddenFor(m => m.Childs[x].CValue2)
</td>
</tr>
}
我还实现了DeleteChild
操作:
public ActionResult DeleteChild(Parent parent, int ChildID){
if (parent != null)
parent.Childs.Remove(parent.Childs.FirstOrDefault(c => c.ID == ChildID));
return View("Index", parent);
}
它仍然缺少所有的数据库代码,但这是下一步
@foreach(ChildItem item in Model.Childs){
<tr>
<td>@item.CValue1</td>
<td>@item.CValue2</td>
</tr>
}
@for(int x = 0; x < Model.Childs.Count; x++){
<tr>
<td>@Html.DisplayFor(m => m.Childs[x].CValue1)</td>
<td>@Html.DisplayFor(m => m.Childs[x].CValue2)</td>
<td> <button type="submit" formaction="DeleteChild" name="ChildID" value="@Model.Childs[x].ID" formmethod="post">X</button>
@Html.HiddenFor(m => m.Childs[x].ID)
@Html.HiddenFor(m => m.Childs[x].CValue1)
@Html.HiddenFor(m => m.Childs[x].CValue2)
</td>
</tr>
}
public ActionResult AddChild(Parent parent, int CValue1, int CValue2){
if (parent.Childs == null)
parent.Childs = new List<ChildItem>();
parent.Childs.Add(new ChildItem(){
ID = parent.Childs.Count, //This will be removed/improved later
CValue1 = CValue1,
CValue2 = CValue2
});
return View("Index", parent);
}
public ActionResult DeleteChild(Parent parent, int ChildID){
if (parent != null)
parent.Childs.Remove(parent.Childs.FirstOrDefault(c => c.ID == ChildID));
return View("Index", parent);
}