【发布时间】:2019-07-26 02:25:41
【问题描述】:
我正在尝试从视图模型中提取用户列表。然后我想点击编辑按钮来编辑该用户。
所以我想用用户 ID 将 get 方法发回控制器,这样我就可以搜索用户 ID 并返回填充了该用户数据的页面,以便对其进行编辑。
我无法从 foreach 循环中获取 id。我只想获取用户 ID,然后将其发回以便我可以找到用户。
我尝试使用隐藏的for,尝试在视图中设置变量。
这是视图模型:
public class AdminPanelViewModel
{
//Just a default constructor
public AdminPanelViewModel()
{
}
//This constructor takes in two lists so we can collect the data to send to view.
public AdminPanelViewModel(List<User> users, List<Post> posts)
{
this.posts = posts;
this.users = users;
}
public List<Post> posts { get; set; }//Geting a bunch of posts
public List<User> users { get; set; }//Getting a bunch of Users
//This is to hold one user from the list
public User user {get; set;}
}
视图本身,到我试图从中提取的 foreach 循环:
@model Blog.ViewModels.AdminPanelViewModel
@{
ViewData["Title"] = "AdminPanel";
Layout = "~/Views/Shared/_Layout.cshtml"; }
<div class="container body">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Users</h1>
<button onclick="location.href='@Url.Action("AddUser", "Blog")'" class="btn btn-lg btn-primary center-block">Add User</button>
</div>
</div>
<!--This is the begining of the Users Section-->
<div class="row">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">User Name</th>
<th scope="col">Manage User</th>
</tr>
</thead>
@using (Html.BeginForm("EditUser", "Blog", FormMethod.Get))
{
<!--This begins the loop through the model to fill in the Users-->
@foreach (var item in Model.users)
{
<tbody>
<tr>
<th scope="row">@item.FirstName</th>
<td>@item.LastName</td>
<td>@item.Email</td>
<td>@item.UserName</td>
<td scope="colgroup">
@Html.HiddenFor(Model => Model.user.UserId, new { Value = item.UserId})
<button type="submit" formaction="EditUser" value="Edit" class="btn btn-sm btn-primary">Edit</button>
<button class="btn btn-sm btn-primary">Delete</button>
</td>
</tr>
</tbody>
}
}
</table>
</div>
它将回发到哪里:
[HttpGet]
public IActionResult EditUser(AdminPanelViewModel adminPanelViewModel)
{
int userID = adminPanelViewModel.user.UserId;
User user = _context.Users.Find(userID);
return View(user);
}
我希望它返回以获取 foreach 循环中用户的用户 ID。
【问题讨论】:
标签: c# entity-framework model-view-controller