Abdul Ahmad
Abdul Ahmad

Reputation: 10021

ajax append multiple times to same div

assuming I have a partial view that is just an editor box for inputting some data (asp.net application)

@Html.Editor("New", new { htmlAttributes = new { @class = "my_editor" } })

in my main view, I have a section that I'd like to update with the partial view I mentioned above using an ajax call.

<div id="editor_section"></div>

My question is, is it possible to continuously append to the same div using the same partial view. In other words, I call ajax once, and a new input box appears. Then I click on the ajax link again, and a second input box appears coming from the same partial view obviously. And I should be able to continue doing this as many times as I like each time appending a new input box under the others.

Upvotes: 0

Views: 1047

Answers (1)

Taylor Burleson
Taylor Burleson

Reputation: 172

Yes it is possible, but it is not very efficient. You should only have to make the AJAX call once, then you can cache the html you get from the partial view in a JavaScript variable, so when you append it later, you don't have to make the round trip to the server to retrieve HTML you have already requested.

Something like:

var inputHtml = null;

var appendInput = function () {
    if (!inputHtml) {
        $.get('/input', function (data) {
            inputHtml = data;
            $('#someDiv').append(inputHtml);
        });
    } else {
        $('#someDiv').append(inputHtml);
    }
};

Upvotes: 2

Related Questions