更新:因为它已保存,所以我想它被调用了两次,并且在某处有代码正在执行此操作。可能与此有关:ASP.NET MVC Action is Called Twice 我检查了jquery和jquery是否有多个实例,但还没有找到。
我想知道为什么这段代码仅在调用action方法时会查找视图“ SaveForm”吗?
它保存得很好(已验证数据库已更新),但是会在后端抛出此错误(用户看不到任何错误)。
这是我的表单标记:
<form asp-controller="Profile" asp-action="SaveForm"
data-ajax="true"
data-ajax-method="POST"
data-ajax-update="#success"
>
<div class="panel panel-input-table panel-input-table-default panel-input-table-condensed">
<div class="panel-heading">
<h3 class="panel-title">Profile</h3>
</div>
<br />
<br />
<div class="panel-body ">
<div class="row">
@await Html.PartialAsync("_OrgStructureLevel", new OrgStructurePathModel { OrgStructureId = null })
</div>
</div>
<br />
<div id="success"></div>
<div class="panel-footer">
<button type="submit" name="btnSave" id="btnSave" class="btn btn-primary btn-save">Save</button>
<a name="btnReset" value="Reset" id="btnReset" href="javascript: location.reload()" class="btn btn-default btn-reset">
Reset
</a>
</div>
</div>
</form>
C#:
namespace IT.Web.Controllers
{
[BreadCrumb(Title = "Profile", UseDefaultRouteUrl = true, Order = 0)]
public partial class ProfileController : BaseController
{
private readonly ITContext _context;
public ProfileController(ITContext dbContext, IConfiguration config) : base(dbContext, config)
{
_context = dbContext;
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SaveForm(int lastNodeIdSelect, int CapsUnit)
{
Profile profile = new Profile
{
UserId = _sessionUser.UserId,
CapsUnitId = CapsUnit,
NodeId = lastNodeIdSelect,
DepartmentId = _sessionUser.DepartmentId
};
using (var db = _context)
{
var userIdExist = (from P in db.Profiles where P.UserId == _sessionUser.UserId select P.UserId).Any();
if (userIdExist)
{
db.Set<Profile>().Update(profile);
db.SaveChanges();
}
else
{
db.Set<Profile>().Add(profile);
db.SaveChanges();
}
}
SessionUser sessionUser = new SessionUser();
sessionUser.CapsUnitId = CapsUnit;
sessionUser.NodeId = lastNodeIdSelect;
HttpContext.Session.Set<SessionUser>("SessionUser", sessionUser);
return View();
}
}
}
错误消息:
出于某种原因,它正在寻找视图SaveForm.cshtml
:
我在return View()
这样的SaveForm
动作方法中尝试了不同的return View("Success");
(我在同一文件夹中有Success.cshtml
),并且得到了:
处理请求时发生未处理的异常。 ObjectDisposedException:无法访问已处置的对象。普通的 导致此错误的原因是处理从 依赖注入,然后尝试使用相同的上下文 实例在您的应用程序中的其他地方。如果您是 在上下文上调用Dispose()或将上下文包装在using中 声明。如果您使用依赖项注入,则应让 依赖项注入容器负责处理上下文 实例。对象名称:“ ITContext”。 Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
答案 0 :(得分:0)
这是我的局部视图(它重新加载了_Layout,再次加载了jquery,再次调用了该动作)。在局部视图中需要此:
@{
Layout = null;
}