我有一個ASP.NET MVC項目,我想將文章發佈到數據庫,然後在頁面上顯示文章的片段。當用戶評論時,我還想在保存到數據庫後顯示評論。我爲此使用AJAX,並在這兩種情況下調用OnFailure
和OnSuccess
方法。ASP.NET MVC頁面在使用AJAX時未更新
OnFailure
方法只在保存帖子而不是註釋時觸發(這是因爲即使保存成功,頁面也不會更新)。根本沒有調用OnSuccess
方法,這是因爲我的頁面沒有更新。
我使用jQuery的2.1.4,並有jquery.unobtrusive阿賈克斯腳本在我的項目
這裏是我的代碼加載。
//查看創建後
@using (Ajax.BeginForm("Create", "Post",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "insertnewpostbelow",
InsertionMode = InsertionMode.InsertAfter,
OnSuccess = "postingSucceeded()",
OnFailure = "postingFailed()"
}))
{
//View code left out
}
//服務器端保存後和更新PartialView
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public async Task<PartialViewResult> Create
([Bind(Include = "ID,Title,Message,PostedOn,isAbuse,By")] Post post)
{
if (ModelState.IsValid)
{
var list = new List<Post>();
list.Add(post);
try
{
db.Posts.Add(post);
await db.SaveChangesAsync();
return PartialView("_Posts", list);
}
catch (RetryLimitExceededException)
{
ModelState.AddModelError("", "Unable to login, please try again and contact administrator if the problem persists.");
//If we got this far, model has errors.
ViewBag.By = new SelectList(db.Members, "ID", "FullNames", post.By);
return PartialView("_Posts", post);
}
}
//If we got this far, model has errors.
ViewBag.By = new SelectList(db.Members, "ID", "FullNames", post.By);
return PartialView("_Posts", post);
}
//我的JavaScript文件
function postingSucceeded() {
alert("Posting succeeded.");
}
function postingFailed() {
alert("Posting failured.");
}
//部分。查看更新
<div id="big-posts">
<span id="insertnewpostbelow"></span>
@Html.Partial("_Posts", Model.Posts)
</div>
我錯過了什麼,在此先感謝。
您不需要ajax.beginform參數中的括號,它應該是'OnSuccess =「postingSucceeded」,OnFailure =「postingFailed」' –
謝謝@AlexArt指出。然而,在更改代碼後,我的問題不是固定的 – Dev
您是否也可以分享您的部分視圖。 – MstfAsan