简体   繁体   中英

AJAX to call a partial view

My legacy project in Web Forms would show a panel when the user clicks on a button. My current project is to rebuild this functionality in C# MVC.

This view will use Javascript and AJAX to show a partial view on demand. The code flows properly in the debugger, but does not call the partial view.

I have used SOF posts to set up the JS so that the div containing the partial view is properly shown. What am I missing in the AJAX or elsewhere? (Maybe I need to decorate the target action? Maybe I need to do something in the partial view?)

The relevant portion of the view:

<script type="text/javascript">

//Show the Add Project section.
function NewProject() {
    //1. Reset the Add Project partial view.
    //2. Show the Add Project partial view.
    //3. Put focus into the project title field.
    //4. Hide the button.
    $("#divNewProject").show();
    $.ajax({
        url: "/Organization/AddProject/"
    }).done(function () {
        $("#divNewProject").html(data);
        $("#ProjectTitle").focus();
        $("#ProjectTitle").scrollIntoView();
    });
    $("#divAddProject").hide();
}
</script>

...

<div id="divAddProject">
    @* Button to add a project, showing/hiding a partial view *@
    <button type="button" name="btnAddProject" id="btnAddProject" value="Add" onclick="NewProject()" class="btn">
        <span class="wizard-step-text">Add New Project</span>
    </button>
</div>
<div id="divNewProject" hidden="hidden">
    This is a test. It should start out hidden and later be shown.
</div>

you can do it like this:

function NewProject() {

$("#divNewProject").show();
    $.ajax({
        url: '@Url.Action("AddProject","Organization")',
        success : function(data)
        {

        $("#divNewProject").html(data);
        $("#ProjectTitle").focus();
        $("#ProjectTitle").scrollIntoView();
        $("#divAddProject").hide();

        }
    });


}

The function inside done should have "data" as parameter.

$.ajax({
    url: "/Organization/AddProject/"
}).done(function (data) {
    $("#divNewProject").html(data);
    $("#ProjectTitle").focus();
    $("#ProjectTitle").scrollIntoView();
});

As you debug, set a breakpoint inside the done function. It should hit, and you'll see that you haven't defined the data variable.

It should be:

}).done(function(data) {
    // Do something with data
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM