Search code examples
c#jqueryajaxasp.net-mvc-5page-refresh

How to update page content after success post without page refresh


I have a MVC application and this is my ajax code. I want that my page content update auto without page refresh after success.I saw many article, but I cant find anything useful for me. I have a JStree in which I want to create a new node after success node name automatically update in tree without refresh page.

$(".btn").click(function () {                  
                    var check = $(".newName").val();                   
                    if (check != "") {
                        $.ajax({
                            url: '@Url.Action("EditUserProfile", "Home")',
                            type: "POST",
                            cache: false,
                            data:{ folder:Name,subId:id},
                            success: function (data) {

                            }
                        });
                        e.preventDefault();
                    }

Solution

  • You can update your page content without refresh:

    1. Make sure your method EditUserProfile in Home controller has enough parameters and they have the same name with your ajax method. In this case, they are : folder and subId.

    2. Remove window.location.reload();and get the data.result to check if the response success or not.

    3. Please see my code:

    View

    $.ajax({ url: '@Url.Action("EditUserProfile", "Home")', type: "POST", cache: false, data: { folder: Name, subId: id }, success: function(data) { if (data.result == true) // or something { // success } else { // fail } } });

    Controller

    public JsonResult EditUserProfile(string folder, string subId) {
        // do something
    
        return Json(new {
            result = true; // false or anything else
        });
    }
    

    The reason is you do nothing with data display on your html. Ajax just help you to call the method in Controller but not edit the current display data for you.

    All you have to do:

    • Assign the row with contains your data with an id

    • Use Jquery to update the content of that row after Ajax return a success value.