我正試圖用ajax-beginform調用一個動作。列表的Ajax BeginForm只返回模型的第一個元素或null
這是我的模型:
public class MyViewModel
{
public List<SubViewModel> SubViewModels {get;set;}
}
public class SubViewModel
{
public string Name {get;set;}
public int Age {get;set;}
public bool Active {get;set;}
}
我的看法是這樣的:(我遍歷所有SubViewModel項,並希望在我讓那些回來以後DoAction法)
@model MyViewModel
@using (Ajax.BeginForm("DoAction", "MyController", null, new AjaxOptions() { HttpMethod = "Post" }, new { @class = "search-form", enctype = "multipart/form-data" }))
{
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Active</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.SubViewModels)
{
<tr>
<td><input type="text" name="Name" value="@item.Name" /></td>
<td><input type="text" name="Age" value="@item.Age" /></td>
<td><input type="checkbox" name="Active" value="@item.Active" /></td>
</tr>
}
</tbody>
</table>
<input type="submit" value="OK" />
}
這是我的行動:
[System.Web.Mvc.HttpPost]
public async Task DoAction([FromBody] MyViewModel model)
{
// here model is null
}
它總是打在DoAction
但斷點:
- 如果模型的類型爲
MyViewModel
,則屬性SubViewModels
爲空。 - 如果模型的類型爲
IEnumerable<SubViewModel>
,則該模型爲null。 - 如果模型類型爲
SubViewModel
,則第一個數據集位於參數中。
所以我想,這個ajax行動的正確參數是從SubViewModel
類型。
但我需要MyViewModel
或IEnumerable<SubViewModel>
以獲得所有列出的模型項目。
也請參閱[這個答案](HTTP:// stackoverflow.com/questions/30094047/post-an-html-table-to-ado-net-datatable/30094943#30094943)的解釋和替代使用'EditorTemplate' –