如何将动态创建的局部视图模型数据发布到控制器?
我的模型类包装器:
namespace Diabuddies.DAL
{
public class Exer_Main
{
public Exer_Workout Workout { get; set; }
public Exer_Routine Routine { get; set; }
public Exer_Set Set { get; set; }
}
}
我的控制器生成以下视图(片段):
@model Diabuddies.DAL.Exer_Main
<body>
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset style="width:800px">
<legend>Workout</legend>
<div style="float:left;text-align:right">
<table>
<tr style="justify-content:center">
<td>
Workout Name:
</td>
<td>
@Html.TextBoxFor(x => x.Workout.Name, new { style = "width:100%" })
</td>
</tr>
<tr>
<td>
Description:
</td>
<td>
@Html.TextAreaFor(x => x.Workout.Description)
</td>
</tr>
<tr>
<td>
Wrokout Notes:
</td>
<td>
@Html.TextAreaFor(x => x.Workout.Notes)
</td>
</tr>
</table>
<br />
<div id="AddItem">Add Routine</div>
<div id="RoutineRows">
</div>
<p>
<input type="submit" value="Create" />
</p>
</div>
</fieldset>
}
<script>
$(document).ready(function(){
$("#AddItem").click(function () {
//alert("Handler for .click() called.");
$.get( '@Url.Action("AddRoutineHTML", "Default", new { id = "ert" })', function(data) {
$('#RoutineRows').append(data);
});
});
});
</script>
每次用户点击“添加行”时,都会添加以下部分视图:
@model Diabuddies.Models.Exer_Routine
<fieldset>
<legend>Routine</legend>
<table>
<tr style="justify-content:center">
<td>
Routine Name:
</td>
<td>
@Html.TextBoxFor(r => r.Name, new { style = "width:100%" })
</td>
</tr>
<tr>
<td>
Description:
</td>
<td>
@Html.TextAreaFor(x => x.Description)
</td>
</tr>
<tr>
<td>
Notes:
</td>
<td>
@Html.TextAreaFor(x => x.Notes)
</td>
</tr>
</table>
</fieldset>
问题在于:如何将动态创建的局部视图发布到控制器?现在我有:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewWorkout([Bind(Prefix = "Workout", Include = "Name, Description")]Exer_Workout eWO, List<Exer_Routine> eR)
{
//Exer_Workout stuff returns fine, I am lost on how to get the partial view data here.
Response.Write(eR.Count); //Program breaks here, nulled out. Obv list isn't answer
return View();
}
答案 0 :(得分:2)
列表是正确的答案。这就是默认模型绑定如何与复杂对象列表一起工作。您将需要输入名称属性中的数组索引,如下所示:
<input type="text" name="Exer_Routine[0].Name" />
对于每个加载的部分,您需要将索引增加1.您可能需要编写自定义HTML而不是使用帮助程序。我建议通过硬编码列表并首先使模型绑定工作来尝试。然后,您可以了解如何生成动态HTML。
希望这有帮助。