简体   繁体   English

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

[英]How to load a partial view containing JavaScript?

In one of my View pages I have a asp.net mvc PartialView. 在我的一个View页面中,我有一个asp.net mvc PartialView。 The PartialView contains some javascript (and jquery). PartialView包含一些javascript(和jquery)。 In my asp.net main View I load the PartialView using ajax, within a div tag, in way given below. 在我的asp.net主视图中,我使用ajax在div标签内加载PartialView,如下所示。 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. 也就是说,从控制器I返回PartialView(“_ DonorEdit”),在我的主页面中,我使用javascript将Part标签的内容替换为PartialView响应。

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

Everything works fine except the javascript contained in the partialView (_DonorEdit). 除了partialView(_DonorEdit)中包含的javascript之外,一切正常。 Thus the question boils down to - How do I have javascript embedded in an div tag and still get it working correctly. 因此,问题归结为 - 如何在div标签中嵌入javascript并仍然使其正常工作。

This problem occurs only when the partial view is returned from the ajax call. 仅当从ajax调用返回部分视图时,才会出现此问题。 In the above code, if I directly include the PartialView (on non-ajax request), then the javascript works properly. 在上面的代码中,如果我直接包含PartialView(在非ajax请求上),那么javascript正常工作。 But if I later replace the content of div using ajax request, the javascript included in PartialView does not work. 但是如果我稍后使用ajax请求替换div的内容,则PartialView中包含的javascript不起作用。 The embedded javascript simply does not appear along with the Partial View. 嵌入式javascript根本不会与“部分视图”一起显示。 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请求成功之后,部分视图中嵌入的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>

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. 解决问题的另一种方法是在控制器中渲染局部视图,返回json对象中的html作为ajax调用结果。

In the Controller, you can have a generic method to render a partial view: 在Controller中,您可以使用通用方法呈现部分视图:

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, ie: 然后,您将不得不向控制器添加一个新的操作方法,返回渲染的视图,即:

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. 希望能帮助到你。

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. 看看它是否有帮助。

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. 您可以使用require.js之类的东西来简化对此的管理。 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的替代,您可以使用像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 extremely powerful and maintainable. 从长远来看,你可能想要看看的是knockout.js:在_DonorEdit.js文件中创建一个viewmodel,它与你局部返回的模板绑定,可以非常强大和可维护。 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的事件绑定。

在你的ajax成功部分调用javascript函数

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

相关问题 如何在部分视图中加载 JavaScript Css 文件 - How to load JavaScript Css files in partial view Rails 5:如何在部分HTML视图中加载Datatable JavaScript - Rails 5: How to load Datatable javascript in partial html view 如何动态加载局部视图内的外部javascript? - how to load external javascript inside partial view dynamically? 如何在嵌套在视图内的部分视图内加载javascript文件? MVC5 - How do I load my javascript file inside my partial view that is nested inside a view? MVC5 如何使用javascript在MVC项目中加载视图,然后加载其中的部分视图? - How do I load a view and then a partial view within it in a MVC project using javascript? 如何将部分视图加载到Bootstrap 4模式中 - How to load Partial View into Bootstrap 4 modal 如何在Ajax调用中的iframe中加载部分视图? - How to load a partial view in an iframe on ajax call? 单击链接时如何加载局部视图? - How to load partial into view when a link is clicked? 如何通过单击表中的一行来加载局部视图 - How to load a partial view by clicking a row in the table 如何在Chrome开发者工具中的JavaScript调试的部分视图中调试脚本? - How to debug a script inside partial view that load by javascript in Chrome Developer Tools?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM