我有一个 ASP.NET MVC 项目,我想将一篇文章发布到数据库,然后在页面上显示文章的片段。当用户评论时,我也想在保存到数据库后显示评论。我为此使用 AJAX 并在这两种情况下调用 OnFailureOnSuccess 方法。
OnFailure 方法仅在我保存帖子而不是评论时启动(这是因为即使我成功保存页面也不会更新)。 OnSuccess 方法根本没有被调用,这是因为我的页面没有更新。

我正在使用 jquery 2.1.4 并且有 jquery.unobtrusive-ajax 脚本加载

这是我的代码。

//创建帖子的 View

 @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.");
}

//要更新的 View 部分
<div id="big-posts">
        <span id="insertnewpostbelow"></span>

        @Html.Partial("_Posts", Model.Posts)
    </div>

我错过了什么,提前致谢。

最佳答案

您需要将返回的局部 View 的内容放在页面的某个位置

<div id="big-posts">
   <span id="insertnewpostbelow"></span>
   <div id="newPost"></div>
</div>

在回调函数上尝试:
function postingSucceeded(data) {
    $("#newPost").html(data);
}

希望这可以帮助!

关于javascript - 使用 AJAX 时未更新 ASP.NET MVC 页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32798219/

10-17 02:00