如何在ASP.NET MVC中将模型作为参数传递给[HttpPost]ActionMethod



我有一个普通的网格,它有编辑和保存按钮。当我从网格中单击Edit链接时,它会转到Edit操作方法,在那里我可以读取Id作为参数。我在想,既然我可以传递Id,那么为什么不将整个模型作为参数传递给Edit操作呢?然而,我总是得到null。我看了一些例子,它们都显示传递id而不是模型对象。我想知道为什么模型不能通过?即使在调试代码时,我总是看到项行与项中的参数Student绑定。

带有编辑链接的网格视图:

@model IEnumerable<MVC_BasicTutorials.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentId, std=item }) |

</td>
</tr>
}
</table>

控制器动作方式:

// Get
public ActionResult Edit(int Id, Student std)
{
var checkSet=std; // coming null
var checkId=Id;  //i am seeing the id value
return RedirectToAction("Index");
}

尝试以下操作:

public ActionResult Index()
{
var model = /* prepare view data model */;
return View(model);
}
[HttpPost]
// The second parameter `Id` is removed because of the `Student` already contains it.
public ActionResult Edit(Student std)
{
System.Diagnostics.Debug.WriteLine($"Id= {std.StudentId}, Student Name= {std.StudentName} ");
return RedirectToAction("Index");
}

Index.cshtml中,您可以使用Html.BeginForm辅助方法来指定表单的目标是"编辑"操作方法。

@model IEnumerable<MVC_BasicTutorials.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
using (Html.BeginForm("Edit", "Home"))
{
@* Prepare a hidden data context to the able the MVC data binding work correctly *@
@Html.Hidden("StudentId", item.StudentId)
@Html.Hidden("StudentName", item.StudentName)
@Html.Hidden("Age", item.Age)
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@*@Html.ActionLink("Edit", "Edit", new { id = item.StudentId, std = item }) *@
<input type="submit" value="Edit" />
</td>
</tr>
}
}
</table>

最新更新