ASP.NET MVC Page not Updated when using AJAX
Asked Answered
D

3

11

I have an ASP.NET MVC project where I want to post an article to the database then display a snippet of the article on the page. When a user comments, I also want to display the comment once I have saved to the database. I am using AJAX for this and call OnFailure and OnSuccess methods in both cases.

The OnFailure method only fires up when I save a post and not a comment (this is because the page isn't updated even when I save successfully). The OnSuccess method isn't invoked at all which is because my page isn't updated.

I am using jquery 2.1.4 and have jquery.unobtrusive-ajax script loaded in my project

Here is my code.

//View for creating a post

 @using (Ajax.BeginForm("Create", "Post",
new AjaxOptions
{
    HttpMethod = "POST",
    UpdateTargetId = "insertnewpostbelow",
    InsertionMode = InsertionMode.InsertAfter,
    OnSuccess = "postingSucceeded()",
    OnFailure = "postingFailed()"
}))
 {
  //View code left out 
 }

//Server side for saving post and updating 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);
    }

//My JavaScript file

    function postingSucceeded() {
    alert("Posting succeeded.");
}

function postingFailed() {
    alert("Posting failured.");
}

//Portion of the View to update

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

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

What am I missing out, thanks in advance.

Darrelldarrelle answered 26/9, 2015 at 14:26 Comment(7)
You don't need parenthesis in ajax.beginform parameters it should be OnSuccess = "postingSucceeded", OnFailure = "postingFailed"Meemeece
Thanks @AlexArt for pointing that out. However after changing the code, my problem isn't fixedDarrelldarrelle
can you share your partial view too.Omentum
@AlexArt. no difference.Lament
@Dennis i need to see _Posts.cshtml can you share thatOmentum
make sure you have one element on page with id that you are updating after ajax callIngle
onFailure will fire when your ajax call failed (means some error occured in action)Ingle
L
4

This is because you have an Ajax form in _Posts PartialView. After the placement, say, after <span id="insertnewpostbelow"></span> you need to run jquery.unobtrusive-ajax on page again.

Note that the scripts will render on page loads, not after any changes in page (like updates by PartialView).

Solution: call the script again, after the page update :)

Lament answered 1/10, 2015 at 8:34 Comment(0)
P
4

You need to put the content of the returned partial view somewhere on the page

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

On the call back function try:

function postingSucceeded(data) {
    $("#newPost").html(data);
}

Hope this helps!

Poussin answered 2/10, 2015 at 11:50 Comment(0)
C
2

First thing you don't need to have parenthesis

OnSuccess = "postingSucceeded()"
                            ^^^

OnFailure = "postingFailed()"
                         ^^^

just

OnSuccess = "postingSucceeded",
OnFailure = "postingFailed"

and now HTML code

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

and javascript code out side the $(document).ready(....)

function postingSucceeded(newPosts) {
    $("#AppendPostsHere").html(newPosts);
}

hope this willl work!

Commerce answered 6/10, 2015 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.