【发布时间】:2019-08-25 15:45:56
【问题描述】:
我在View 的HTML 表中显示了一些数据。现在,我想做的是在单击按钮时(比如SUBMIT 按钮,我想将数据发送到控制器的 POST 方法,以便我可以将数据保存到数据库中。
我尝试使用Model Binding 技术获取数据,但是,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; }
}
所以,我有一个名为MyModel.cs 的Model,它是数据库中的表。然后,我有一个名为ViewModel 的MyViewModel.cs' that has the same columns as theModel, in addition to some columns, plus aListofMyModeltype. Then, there is anotherViewModelcalledVMList.csthat contains a list of tuples ofMyViewModeltype. ThisViewModelis passed to theView`。
View 的构造方式如下:
查看
@model ...Models.ViewModels.VMList
...
<form asp-action="MyAction" asp-controller="MyController" id="myForm">
<div>
<button type="submit" value="submit" id="submitButton">Submit</button>
<table id="myTable">
@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>
@item.FirstName
</td>
<td>
@item.LastName
</td>
<td>
@item.Header3
</td>
</tr>
@if(item.subList != null && item.subList.Count() != 0)
{
<thead>
<tr>
<th>SubList Header 1</th>
<th>SubList Header 2</th>
<th>SubList Header 3</th>
</tr>
</thead>
<tbody>
@foreach(var subItem in item.subList)
{
<tr>
<td>
@subItem.SubListHeader1
</td>
<td>
@subItem.SubListHeader2
</td>
<td>
@subItem.SubListHeader3
</td>
</tr>
}
</tbody>
}
}
</table>
</div>
</form>
POST 方法
[HttpPost]
public IActionResult MyAction(VMList vmListObject)
{
return View();
}
如何将View 中的表中显示的数据返回到Controller?
【问题讨论】:
-
首先,要从表单向控制器提交任何数据,您需要输入字段。我在您的表单中没有看到任何输入字段。其次,您的表单操作是
MyController.MyAction,但在您的 post 方法中,您显示了Index方法。 -
我很抱歉。那是一个错字。我已经在代码中更正了它。在实际代码中是正确的,因为我在单击提交按钮时调用了 POST 方法。
-
MyAction方法看起来仍然不正确,因为它不接受任何参数,请在此处粘贴您的实际代码。 -
又是一个愚蠢的错字Priyank。我很抱歉。我应该在发布之前修改代码。但是,在实际代码中是正确的。
-
现在回到我的第一个问题,您需要输入字段来提交表单中的任何内容。您可以为要提交给控制器的
<td>中的每个值创建一些隐藏字段。但是,要使其正确,您必须正确命名它。我建议你看看编辑器模板一次。
标签: c# asp.net-mvc asp.net-core-mvc viewmodel