griegs
griegs

Reputation: 22770

PartialView not clearing after ajax postback

I have this weird thing happening.

I have a PartialView with 3 fields on it. I do a jQuery ajax post to my action result and if the model passes validation i save the record. I also then set the model to empty and pass it back to the view as a partial view.

    public ActionResult jQueryAddComment(Comment comment)
    {
        if (ModelState.IsValid)
        {
            //do stuff here
            comment = new Comment();
        }

        return PartialView("AddNewComment", comment);
    }

When I get back to the page my JS replaces the contents of the comments div with the html from the new partial view.

    function submitComment() {
        $.post('/Home/jQueryAddComment', { forumItemId: $('#id').val(), owner: $('#owner').val(), text: tinyMCE.get('text').getContent(), emailAddress: $('#emailAddress').val() }, function (result) {
            alert(result);
            $('.AddNewComment').html(result);
        });            
    }

However, when the page renders the values are back in place. I can see that an empty model is being passed to the view so why are my previous values still there?

Even the alert shows the values in place even though I'm passing an empty object to the partial view in the controller.

edit

I should mention that I can't clear the fields within the JS of the page as I want to use the same code to render errors as well as successful requests.

Upvotes: 1

Views: 4167

Answers (2)

Safran Ali
Safran Ali

Reputation: 4497

Use ModelState.Clear() before returning the new blank model as a partial view, like:

if (ModelState.IsValid)
{
    //your save logic

    ModelState.Clear();
    comment = new Comment();
}

return PartialView("AddNewComment", comment);

Upvotes: 4

John Farrell
John Farrell

Reputation: 24754

The standard HTML helpers look into ModelState and ViewData for values before using the values you passed to the helper.

This may help: How to clear textboxes defined with MVC HTML helpers

Upvotes: 3

Related Questions