[英]How to pass model as a parameter to [HttpPost] ActionMethod in ASP.NET MVC?
我有一个通常的网格,它有编辑和保存按钮。 当我从网格中单击Edit
链接时,它转到Edit
操作方法,我可以在其中读取Id
作为参数。 我在想,既然我可以传递 ID,那么为什么不将整个 model 作为参数传递给Edit
操作呢? 但是,我总是得到null
。 我查看了一些示例,它们都显示传递 id 而不是 model object。 不知为何model不能通过? 即使当我调试代码时,我总是看到项目行与项目中的参数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>
Controller动作方法:
// 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
中:
@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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.