我正在使用实体框架核心数据库-首先,我有一个用户项目模型与多对多的关系,我正在做控制器更新它,但我怎么能做到这一点使用复合键,当我在控制器中跟踪编辑方法它总是发送Null在编辑后!我做错了什么?我该如何补救?
控制器:
public async Task<IActionResult> Edit(int? user_id, int? project_id)
{
if (user_id == null && project_id == null )
{
return NotFound();
}
var userPoject = await _context.UserPojects.FindAsync(user_id , project_id);
if (userPoject == null)
{
return NotFound();
}
ViewData["ProjectId"] = new SelectList(_context.Projects, "ProjectId", "ProjectName", userPoject.ProjectId);
ViewData["UserId"] = new SelectList(_context.Users, "UserId", "UserName", userPoject.UserId);
return View(userPoject);
}
[HttpPut]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? user_id , int? project_id, [Bind("UserId,ProjectId,UserRoles")] UserPoject userPoject)
{
if (project_id != userPoject.ProjectId && user_id != userPoject.UserId)
{
return NotFound();
}
_context.Entry(userPoject).State = EntityState.Modified;
if (ModelState.IsValid)
{
try
{
_context.Update(userPoject);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserPojectExists(userPoject.UserId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["ProjectId"] = new SelectList(_context.Projects, "ProjectId", "ProjectName", userPoject.ProjectId);
ViewData["UserId"] = new SelectList(_context.Users, "UserId", "UserName", userPoject.UserId);
return View(userPoject);
}
视图指数:
<td>
@Html.ActionLink("Edit", "Edit", new { user_id = item.UserId , project_id =item.ProjectId }) |
@Html.ActionLink("Details", "Details", new { id = item.UserId }) |
@Html.ActionLink("Delete", "Delete", new { user_id = item.UserId, project_id = item.ProjectId })
</td>
编辑视图:
@model SystemAdminDBFApp.Models.UserPoject
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>UserPoject</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="UserId" />
<input asp-for="ProjectId" />
<div class="form-group">
<label asp-for="UserRoles" class="control-label"></label>
<input asp-for="UserRoles" class="form-control" />
<span asp-validation-for="UserRoles" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
我在控制器中跟踪编辑方法,它总是在编辑后发送Null !
user_id
和project_id
哪个值为空?您提供的表单似乎没有为它们包含字段,它们是必要的吗?
另外,html表单标签只支持GET
和PUT
方法,而编辑是put方法,您可以将其更改为post。