如何加载包含 JavaScript 的部分视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7319238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:47:19  来源:igfitidea点击:

How to load a partial view containing JavaScript?

javascriptjqueryasp.net-mvcasp.net-mvc-3

提问by Jatin

In one of my View pages I have a asp.net mvc PartialView. The PartialView contains some javascript (and jquery). In my asp.net main View I load the PartialView using ajax, within a div tag, in way given below. That is, from controller I return PartialView("_DonorEdit") and in my main page I use javascript to replace the content of the div tag with the PartialView response.

在我的一个视图页面中,我有一个 asp.net mvc PartialView。PartialView 包含一些 javascript(和 jquery)。在我的 asp.net 主视图中,我使用 ajax 加载 PartialView,在 div 标签内,如下所示。也就是说,我从控制器返回 PartialView("_DonorEdit") 并在我的主页中使用 javascript 将 div 标记的内容替换为 PartialView 响应。

<div class="content" id="content">
    @{Html.RenderPartial("_DonorEdit");}   
</div>

Everything works fine except the javascript contained in the partialView (_DonorEdit). Thus the question boils down to - How do I have javascript embedded in an div tag and still get it working correctly.

除了partialView(_DonorEdit)中包含的javascript之外,一切正常。因此,问题归结为 - 如何将 javascript 嵌入到 div 标签中并仍然使其正常工作。

This problem occurs only when the partial view is returned from the ajax call. In the above code, if I directly include the PartialView (on non-ajax request), then the javascript works properly. But if I later replace the content of div using ajax request, the javascript included in PartialView does not work. The embedded javascript simply does not appear along with the Partial View. So there seems to be some other reason, why the javascript embedded in Partial View does not get passed to browser after the ajax request success.

仅当从 ajax 调用返回局部视图时才会出现此问题。在上面的代码中,如果我直接包含 PartialView(在非 ajax 请求上),那么 javascript 就可以正常工作。但是如果我稍后使用ajax请求替换div的内容,则PartialView中包含的javascript不起作用。嵌入的 javascript 不会与部分视图一起出现。所以似乎还有一些其他原因,为什么在 ajax 请求成功后嵌入在 Partial View 中的 javascript 没有传递给浏览器。

The part of my javascript code

我的 javascript 代码的一部分

<script type=...>
//Date Picker. This works. I get Calendar popup as expected

$(document).ready(function () {
    $("#Donor_BirthDate").datepicker({
        dateFormat: "dd-mm-yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "-75:+0"
    });

    $("#Donor_DateLastDonated").datepicker({
        dateFormat: "dd-mm-yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "-20:+1"
    });
});


//Dropdown handler. Does not make it in my final View.

function residenceStateChanged(e) {
    var url = '@Url.Action("_GetCities", "DropDown")';
    var cmbResidenceCityId = $('#ResidenceCityId').data('tDropDownList');
    cmbResidenceCityId.loader.showBusy();

    $.ajax({
        type: 'GET',
        url: url,
        data: { StateId: e.value, AddSelectOption: true, SelectOption: 'Select' },
        traditional: true,
        success: function (resp, textStatus, jqXHR) {
            cmbResidenceCityId.dataBind(resp);
            cmbResidenceCityId.select(0);
            cmbResidenceCityId.trigger.change();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        },
        complete: function () {
            cmbResidenceCityId.loader.hideBusy();
        }
    });
}

....//Some other code omitted. Does not make it in final view.
</script>

回答by Garrett Vlieger

I believe your problem is related to this one:

我相信你的问题与这个有关:

Calling a jQuery function inside html return from an AJAX call

从 AJAX 调用返回的 html 中调用 jQuery 函数

Take a look and see if it helps.

看看它是否有帮助。

回答by thepirat000

Another way to solve the problem, is to render the partial view in the controller, an return back the html in a json object, as the ajax call result.

另一种解决问题的方法是在控制器中渲染局部视图,将 html 返回到 json 对象中,作为 ajax 调用结果。

In the Controller, you can have a generic method to render a partial view:

在控制器中,您可以使用通用方法来呈现局部视图:

private string RenderPartialView(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
    {
        viewName = this.ControllerContext.RouteData.GetRequiredString("action");
    }
    this.ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
        var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

Then, you will have to add a new action method to your controller that returns the rendered view, i.e.:

然后,您必须向控制器添加一个新的操作方法,该方法返回呈现的视图,即:

public JsonResult GetDonorEdit()
{
    return Json(new 
    { 
        DonorEditContent = RenderPartialView("_DonorEdit", null) 
    });
}

In client side, the ajax call can be changed to something like this:

在客户端,ajax 调用可以改成这样:

$.ajax({
    type: "POST",
    url: "GetDonorEdit",  // get the correct url of GetDonorEdit action
    cache: false
})
.success(function (result) {
    $("#content").html(result.DonorEditContent); 
})
.error(function (xhr, errStatus, errThrown) {
    //...
});

I use this technique, because usually have to return more than one partial view in the same ajax call, and also because it properly execute the javascript code inside the partial views.

我使用这种技术,因为通常必须在同一个 ajax 调用中返回多个分部视图,还因为它正确执行分部视图中的 javascript 代码。

Hope it helps.

希望能帮助到你。

回答by Chad Ruppert

If you are using this function in multiple pages, why not include it in a script file (maybe named _DonorEdit.js) and including for those pages that use the partial?

如果您在多个页面中使用此函数,为什么不将其包含在脚本文件(可能名为 _DonorEdit.js)中并包含那些使用部分的页面?

You could use something like require.js to make management of this easier. Alternatively to require.js you can use asset bundling like Cassette.net to manage the dependencies for the pages and any partials you load via ajax.

你可以使用 require.js 之类的东西来简化管理。作为 require.js 的替代方案,您可以使用资产捆绑(如 Cassette.net)来管理页面的依赖项以及您通过 ajax 加载的任何部分。

Then, like in your binding/trigger calls inside of your ajax success handler, you can register whatever events/handlers you need to for the partial.

然后,就像在 ajax 成功处理程序内的绑定/触发器调用中一样,您可以为部分注册所需的任何事件/处理程序。

In the long term something you might want to look at is knockout.js: creating a viewmodel in that _DonorEdit.js file that binds against a template returned in your partial can be extremelypowerful and maintainable. If you prefer to still render all the data for the partial serverside, you can still take advantage of knockout's event binding to some degree.

从长远来看,您可能想要查看 Knockout.js:在 _DonorEdit.js 文件中创建一个视图模型,该文件绑定到您的部分中返回的模板可能非常强大且可维护。如果您仍然希望为部分服务器端呈现所有数据,您仍然可以在一定程度上利用淘汰赛的事件绑定。

回答by learning

Call the javascript function in your ajax success part

在 ajax 成功部分调用 javascript 函数