Repeat partial view Jquery + MVC 5

74
May 25, 2018, at 11:30 PM

I have a button that calls a partial view in which a table is loaded with all the categories of my system

 <input type="button" value="Cargar Categorias" id="btnCargarCategorias" />

This load is made through a partial view which I charge inside a <div>

 <div id="divTabla">
    </div>

My javascript code that loads the table by clicking on the button is the following...

 <script>
        $("#btnCargarCategorias").click(function () {
            $(this).prop("disabled", "disabled");
            var url = '@Url.Action("CargarCategorias","Categorias")';
            $.get(url).done(function (data) {
                $("#divTabla").append(data);
            })
            $("#btnCargarCategorias").removeAttr("disabled");
        })
    </script>

My action in the controller:

 public PartialViewResult CargarCategorias()
        {
            var categorias = db.Categorias.ToList();
            return PartialView("_TablaCategorias", categorias);
        }

The problem is that when you click the button a second time, it reloads the table below the first one and so on if I keep pressing the button ...

Expected behavior: regardless of the times you click on the button, the table is loaded in the same place

behavior obtained: each time the button is pressed, a new table is loaded below the previous one

What do I have to do in my code to obtain the desired behavior? I have to occupy Ajax technology? any help for me?

Answer 1

Because you did not clear you div before appending data into it.

You may do the following

$.get(url).done(function (data) {
    $("#divTabla").html("");
    $("#divTabla").html(data);
})

Which will clear the inner body of the div, and then put the data inside.

READ ALSO
Different ways i could append my JavaScript array

Different ways i could append my JavaScript array

I have a array of in the following format

55
Resize Header onscroll React

Resize Header onscroll React

I need to basically rewrite this codepen in reacthttps://codepen

70
passing referer from the client and getting the headers.referer in node.js

passing referer from the client and getting the headers.referer in node.js

I have several sites, I want to check which site call my api, I did this in nodejs

78
Using keydown event with d3.drag () to rotate a SVG

Using keydown event with d3.drag () to rotate a SVG

I have a SVG and I want to apply rotation transformation on it but not just with the mouse drag, instead with a mouse drag while pressing the alt keyI have tried to implement something but things donot seem to work as I want

55