简体   繁体   English

AJAX调用局部视图

[英]AJAX to call a partial view

My legacy project in Web Forms would show a panel when the user clicks on a button. 当用户单击按钮时,我在Web窗体中的旧项目将显示一个面板。 My current project is to rebuild this functionality in C# MVC. 我当前的项目是在C#MVC中重建此功能。

This view will use Javascript and AJAX to show a partial view on demand. 该视图将使用Javascript和AJAX显示按需的局部视图。 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. 我已经使用SOF帖子来设置JS,以便正确显示包含部分视图的div。 What am I missing in the AJAX or elsewhere? 我在AJAX或其他地方缺少什么? (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. 在调试时,请在done函数中设置一个断点。 It should hit, and you'll see that you haven't defined the data variable. 它应该会命中,您会看到尚未定义data变量。

It should be: 它应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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