在传统MVC和.net核心之间的转换中,当我在两种技术中使用几乎相同的代码时,我遇到了一些古怪的东西。
我将id字段的参数和发送控制器的名称从视图传递到接收控制器。下面的代码适用于传统的MVC:
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
@Html.ActionLink("New Comment", "Create", "ServiceRequestNotes", new { ServiceRequest = item.Id, returncontroller = "ServiceRequests" }, null)<br />
</td>
并且
// POST: ServiceRequestNotes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,NoteDescription,LastUpdated,WrittenBy,ServiceRequest")] ServiceRequestNote serviceRequestNote, string returncontroller)
{
if (ModelState.IsValid)
{
db.ServiceRequestNotes.Add(serviceRequestNote);
serviceRequestNote.LastUpdated = DateTime.Now;
serviceRequestNote.WrittenBy = User.Identity.Name;
await db.SaveChangesAsync();
//return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
return RedirectToAction("Index", returncontroller);
}
ViewBag.ServiceRequest = new SelectList(db.ServiceRequests, "Id", "RequestHeading", serviceRequestNote.ServiceRequest);
return View(serviceRequestNote);
}
当我调试并且成功保存
时,立即填充returncontroller值我在.net Core中的代码几乎相同
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a> |
@Html.ActionLink("New Comment", "Create", "ServiceRequestNotes", new { ServiceRequest = item.Id, returncontroller = "TeamServiceRequests" }, null)<br />
</td>
和
// POST: ServiceRequestNotes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,NoteDescription,LastUpdated,WrittenBy,ServiceRequest")] ServiceRequestNotes serviceRequestNotes, string returncontroller)
{
if (ModelState.IsValid)
{
_context.Add(serviceRequestNotes);
serviceRequestNotes.LastUpdated = DateTime.Now;
serviceRequestNotes.WrittenBy = User.Identity.Name;
await _context.SaveChangesAsync();
//return RedirectToAction(nameof(Index));
return RedirectToAction("Index", returncontroller);
}
ViewData["ServiceRequest"] = new SelectList(_context.ServiceRequests, "Id", "RequestDescription", serviceRequestNotes.ServiceRequest);
return View(serviceRequestNotes);
}
但是在调试中 - 当它到达公共异步创建行时,returncontroller的值为null。
它仍然保存了注释,但由于上面的内容为null,它返回到notescontroller的索引视图而不是原始注释视图。
任何人都知道为什么在.net核心中,当代码几乎相同时,returncontroller值会变为null?感谢