1
如何將動態創建的局部視圖模型數據發佈到控制器?MVC獲取從動態創建的局部視圖發佈到控制器的模型數據
我的模型類包裝:
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();
}
試過但似乎沒有工作。我只是將上述內容添加到了我的部分視圖中,並嘗試傳入一個實例 - 列表仍然爲空。我的模型在局部視圖中是否仍然相同?或更改爲列表? – BriOnH
當您查看源代碼時,您輸入的HTML如下所示:這是獲取列表模型的重要部分[0]對工作有約束力。 – Mark
菲爾哈克的這篇文章也值得一讀:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ – Mark