我在HTML
的{{1}}表中显示了一些数据。现在,我要做的就是单击一个按钮(例如一个View
按钮)后,我想将数据发送到Controller的POST方法,以便可以将数据保存到数据库。
我尝试使用SUBMIT
技术获取数据,但是Model Binding
方法中的ViewModel
对象是POST
。
模型和ViewModel
null
因此,我有一个名为// Model Model.cs
public class MyModel
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
...
}
// ViewModel MyViewModel.cs
public class MyViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
...
public List<MyModel> MyModelList { get; set; }
}
// ViewModel VMList.cs
public class VMList
{
public List<MyViewModel> MyViewModelList { get; set; }
}
的{{1}},它是数据库中的表。然后,我有一个名为Model
Model MyModel.cs
List ViewModel
MyModel MyViewModel.cs' that has the same columns as the
ViewModel , in addition to some columns, plus a
VMList.cs of
MyViewModel { {1}} ViewModel type. Then, there is another
View`。
视图是通过以下方式构造的:
查看
called
POST方法
that contains a list of tuples of
如何将type. This
表中显示的数据返回到is passed to the
?
答案 0 :(得分:2)
根据您提供的模型,尝试使用asp-for
标记帮助程序和name
属性进行模型绑定。
@model VMList
<form asp-action="MyAction" asp-controller="HomeController" id="myForm">
<div>
<button type="submit" value="submit" id="submitButton">Submit</button>
<table id="myTable">
@{ int i = 0;}
@foreach (var item in Model.MyViewModelList)
{
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input asp-for="@item.FirstName" name="vmListObject.MyViewModelList[@i].FirstName" />
</td>
<td>
<input asp-for="@item.LastName" name="vmListObject.MyViewModelList[@i].LastName"/>
</td>
<td>
<input asp-for="@item.Header3" name="vmListObject.MyViewModelList[@i].Header3" />
</td>
</tr>
@if (item.MyModelList != null && item.MyModelList.Count() != 0)
{
<thead>
<tr>
<th>SubList Header 1</th>
<th>SubList Header 2</th>
<th>SubList Header 3</th>
</tr>
</thead>
<tbody>
@{ int j = 0;}
@foreach (var subItem in item.MyModelList)
{
<tr>
<td>
<input asp-for="@subItem.FirstName" name="vmListObject.MyViewModelList[@i].MyModelList[@j].FirstName"/>
</td>
<td>
<input asp-for="@subItem.LastName" name="vmListObject.MyViewModelList[@i].MyModelList[@j].LastName" />
</td>
<td>
test
</td>
</tr>
j++;
}
</tbody>
}
</tbody>
i++;
}
</table>
</div>
</form>