我从几天开始使用MVC,并且在学习MVC中的控制器和视图之间进行通信时遇到了很多问题 我有以表格形式显示员工列表的页面. 模型是Employee Model的IEnumerable类型 它有三个按钮,分别是编辑
我有以表格形式显示员工列表的页面.
模型是Employee Model的IEnumerable类型
它有三个按钮,分别是编辑,创建,删除,详细信息.
需求:
我使用了按钮,所有都应该是HTTP Post请求类型,因为我不希望用户使用URL请求直接访问它们.
这是我的观看代码:
@using (Html.BeginForm())
{
<p>
<input type="submit" name="CreateView" value="Create New(Post)" formaction="CreateView" formmethod="post" />
</p>
<table class="table">
<tr>
-------Headings of table-------
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.EmployeeName)</td>
<td>@Html.DisplayFor(modelItem => item.EmployeeGender)</td>
<td>@Html.DisplayFor(modelItem => item.EmployeeCity)</td>
<td>@Html.DisplayFor(modelItem => item.DepartmentId)</td>
<td>@Html.DisplayFor(modelItem => item.EmployeeDateOfBirth)</td>
<td>
<input type="submit" name="EditView" value="Edit(Post)" formaction="Edit" formmethod="post" /> |
<input type="submit" name="DetailsView" value="Details(Post)" formaction="Details" formmethod="post" /> |
<input type="submit" value="Delete(Post)" onclick="return confirm('Are you sure you want to delete record with EmployeeId = @item.EmployeeId')" />
</td>
</tr>
}
</table>
}
这里删除按钮有效,因为我不需要员工的ID.
但对于编辑,删除和详细信息查看等其他操作,我需要将Employees Id传递给控制器.但是如何使用提交按钮将Id传递给控制器.
在获取请求类型中,我曾经像这样传递:
@Html.ActionLink("Details", "Details", new { id = item.EmployeeId })
对于单个提交按钮,我曾经传递过这样的数据
@using (Html.BeginForm("Details", "BusinessLayer", FormMethod.Post, new { id = item.EmployeeId }))
任何人都可以告诉我我可以尝试实现这一目标的方法吗?
您可以拥有3个单独的表单标签,每个按钮一个.只需确保表单中包含要传递的数据的输入字段.例如,如果您的操作方法接受带有名为EmployeeId的参数的EmployeeId,则您应该在输入隐藏字段中具有相同的表单内部.@model IEnumerable<Employee>
<table>
@foreach(var item in Model)
{
<tr>
<td>@item.EmployeeName</td>
<td>@item.EmployeeGender</td>
<td>@item.EmployeeCity</td>
<td>@item.EmployeeDateOfBirth</td>
<td>
@using(Html.BeginForm("Details","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
<input type="submit" value="Details" />
}
@using(Html.BeginForm("Edit","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
<input type="submit" value="Edit" />
}
@using(Html.BeginForm("Delete","YourControllerName"))
{
<input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
<input type="submit" value="Delete" />
}
</td>
</tr>
}
还要记住,嵌套表单是无效的HTML.所以一定要确保没有.
