Umut Derbentoğlu
Umut Derbentoğlu

Reputation: 1196

Asp.Net MVC Partial View Update Issue

I have an asp.net mvc application. I am trying to update a partial view that is inside main view with ajax post. Here is my javascript code:

$.ajax({
            url: "Interface/GetErrors?servers=" + serverNames,
            type: "Post",
            dataType: "html",
            async: false,
            success: function (result) {
                $('#errorListDiv').html(result);
            },
            error: function () {
                alert("Error occured");
            }
        });

Actually this ajax post gets partial view successfully. But my problem is; after partial view loads, some css classes, html attributes etc. loads incomplete. Because some parts of partial views are arranged and created with javascript functions. Because of this javascript libraries render in main view or viewstart and this libraries will not be rendered with ajax post, my partial view loads incomplete. How can I achieve this?

Upvotes: 0

Views: 252

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

I mentioned a few methods in my comments. Here is the one you may need:

Extract any <script> blocks from the raw HTML and cause them to execute. I believe html() strips out script blocks.

$.ajax({
    url: "Interface/GetErrors?servers=" + serverNames,
    type: "Post",
    dataType: "html",
    success: function (result) {
        $('#errorListDiv').html(result);
        var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
        var scripts = "";
        var match;
        while (match = re.exec(result)) {
            if (match[1] != "") {
                scripts += match[0];
            }
        }
        // cause the scripts to execute - add them to the panel loaded
        $('#errorListDiv').append(scripts);
    },
    error: function () {
        alert("Error occured");
    }
});

You will need to ensure your partial views only contains blocks of script code and not script file references or you may double-up on your includes.

There may well be a better way to do this, but this worked for me, so I am happy to hear comments.

*Note: Please do not ever use async: false. It causes any numebr of additional problems for little benefit. Just use the async callbacks provided (which you are anyway).

Upvotes: 1

Related Questions