简体   繁体   English

在ASP .NET MVC中敲除html绑定不起作用(绑定到调用局部视图的函数)

[英]Knockout html binding not working (bound to a function calling a partial view) in ASP .NET MVC

I have an ASP .NET MVC application, additonally I am using Knockout 2.0.0. 我有一个ASP .NET MVC应用程序,另外我正在使用Knockout 2.0.0。 I created a partial view which I would like to render to the page using knockout. 我创建了一个局部视图,我想使用knockout渲染到页面。 The partial needs to be rendered within a Knockout foreach statement. 部分需要在Knockout foreach语句中呈现。 I am unable to get the knockout HTML binding to work, and so I'm currently using a hack to put the html into the div using JQuery. 我无法让淘汰HTML绑定工作,所以我目前正在使用hack将html放入div中使用JQuery。

There is a lot of html on this page, so it's not possible to post all of the source code, so I will try and post the pertinent code: 这个页面上有很多html,因此无法发布所有源代码,因此我将尝试发布相关代码:

<div data-bind="foreach:issues">
    @* SNIP - A lot of other html here*@
    <div id="myPartialDiv" data-bind="html: $parent.getHtml(issueId())">
    </div>  
</div>

Further down I have the following javascript function on my KO View Model (I have commented out my hack and included the code that returns HTML): 再往下我在我的KO View模型上有以下javascript函数(我已经注释掉了我的hack并包含了返回HTML的代码):

   var getHtml = function (issueId) {
              var baseUrl = '@Url.Action("GetHtmlAction","MyController")';
              $.ajax(
                {
                    type: "POST",
                    url: baseUrl,
                    data: "&issueId=" + issueId,
                    success: function (data) {
                        //$('#mypartialDiv').html(data);                          
                        return data;
                    },
                    error: function (req, status, error) {
                        //$('#myPartialDiv').html('Something went wrong.');
                        return 'Something went wrong.'
                    },
                    dataType: "text"
                });
         }

The code above results in no data being rendered to the page. 上面的代码导致没有数据呈现给页面。 USing Chrome debug tools, I see that there are no javascript errors occuring, and knockout is simply not binding the html of the div to the results returned from the getHtml function. 使用Chrome调试工具,我发现没有javascript错误发生,并且knockout只是没有将div的html绑定到getHtml函数返回的结果。

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

As Miroslav Popovic explains, the problem is that the AJAX request is asynchronous, so the return data is ignored and there is no return value from your call to getHtml . 正如Miroslav Popovic所解释的那样,问题是AJAX请求是异步的,因此return data被忽略,并且调用getHtml没有返回值。

I would suggest using a custom binding that handles the asynchronous HTML loading (I've put a working example here ). 我建议使用一个处理异步HTML加载的自定义绑定(我在这里放了一个工作示例)。

This works by taking 2 parameters to the asyncHtml: a function to call that takes a success callback as it's final parameter (plus any other parameters) and an array of the parameters that need to be passed to that function. 这通过将两个参数带到asyncHtml来实现:一个调用函数,它接受成功回调,因为它是最终参数(加上任何其他参数)以及需要传递给该函数的参数数组。

<div id="myPartialDiv" data-bind="asyncHtml: { source: getHtml, params: [123] }">Loading...</div>

The custom binding then grabs these values, concats a custom callback onto the parameters that are passed to it, and calls the specified function: 然后,自定义绑定会获取这些值,将自定义回调连接到传递给它的参数,并调用指定的函数:

ko.bindingHandlers.asyncHtml = {
    init: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var parameters = value.params.concat([function(data) {
           $(element).html(data); 
        }]);
        value.source.apply(null, parameters);
    }
};

Finally we can re-implement our view model HTML-retrieving method to make the POST call and invoke the new success handler: 最后,我们可以重新实现我们的视图模型HTML检索方法来进行POST调用并调用新的成功处理程序:

var ViewModel = function() {
    this.getHtml = function(issueId, callback) {
        $.ajax(
            {
                type: "POST",
                url: "/echo/html/",
                data: {
                        html: "<p>server response " + issueId + "</p>",
                        delay: 1
                    },
                success: callback,
                dataType: "text"
            });            
    };
};

Note: for this example I am using the jsFiddle echo to post back a random response 注意:对于此示例,我使用jsFiddle echo回发随机响应

$.ajax is an asynchronous call. $.ajax是一个异步调用。 When you call it, the execution will just continue to the next statement in the getHtml function. 当你调用它时,执行将继续执行getHtml函数中的下一个语句。 Since this is the last statement, the getHtml function will return undefined . 由于这是最后一个语句, getHtml函数将返回undefined

About your return data; 关于您的return data; ... This return is within a success callback function. ...此返回是在成功回调函数内。 The data will be result of that function, not the parent getHtml function. 数据将是函数的结果,而不是父getHtml函数。 Besides, getHtml is already completed. 此外, getHtml已经完成。 You can't return a result from it. 您无法从中返回结果。

How about having an observable property in your view model called html , and then find some other means of triggering the getHtml function (button click, some other success callback, issueId property change...), that will in turn set the 'html' property value. 如何在视图模型中使用名为html的可观察属性,然后找到一些其他触发getHtml函数的方法(按钮单击,其他一些成功回调,issueId属性更改...),这将依次设置'html'适当的价值。 Then you could simply data-bind to that property data-bind="html: html" . 然后你可以简单地数据绑定到该属性data-bind="html: html"

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

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