简体   繁体   English

将Javascript中的值返回到C#HTML文件

[英]Returning values in Javascript to C# HTML file

Here is my issue, I have a javascript function in a .js file that performs some actions, gathers information, and uses a callback. 这是我的问题,我在.js文件中有一个javascript函数,该函数执行一些操作,收集信息并使用回调。 The callback function is also a javascript function but resides in a .cshtml file. 回调函数也是javascript函数,但是驻留在.cshtml文件中。 I am have difficulties returning a value from my .js javascript function to my .cshml javascript callback function. 我很难将.js javascript函数的值返回到.cshml javascript回调函数。

Here is a little sample code... 这是一些示例代码...

my .js function which I would like to return a value from: 我的.js函数,我想从中返回一个值:

function returnVal(itemID, onCompleteCallback) {
//get vals from DB
onCompleteCallback();
}

my .cshtml script that calls the previous function and I need to get the returned value is a button click even: 我的调用前一个函数的.cshtml脚本,我需要获取返回的值是单击按钮,甚至:

updateBtn.onclick = function(e) {
if(action==1) {
    returnVal(itemID, OnCompleted);
}

I have tried 2 methods, neither has worked. 我尝试了2种方法,但都没有奏效。 I have tried returning a value within the "returnVal" function which doesn't seem to results in anything being returned. 我尝试在“ returnVal”函数中返回一个值,该值似乎不会导致任何返回。 I have also tried passing a variable as type var and setting it within the returnVal function, it was my understanding that primitives are passed by value (and thus this wouldn't work) but objects are passed by reference and so I thought this would work. 我也尝试过将变量设为var类型并将其设置在returnVal函数中,这是我的理解,即基元是通过值传递的(因此这是行不通的),而对象是通过引用传递的,所以我认为这是可行的。 At any rate, neither was successful. 无论如何,都没有成功。 Bellow are examples of how I have tried the aforementioned 2 methods: 贝娄是我尝试上述两种方法的示例:

Method 1: 方法1:

function returnVal(itemID, onCompleteCallback) {
//get vals from DB
onCompleteCallback();
return x;
}

updateBtn.onclick = function(e) {
    if(action==1) {
        x = returnVal(itemID, OnCompleted);
    }
}

Method 2: 方法2:

   function returnVal(x, itemID, onCompleteCallback) {
    //get vals from DB
    onCompleteCallback();
    }

updateBtn.onclick = function(e) {
    if(action==1) {
        var x;
        returnVal(x, itemID, OnCompleted);
    }
}

In both cases 'x' is not set. 在两种情况下均未设置“ x”。 I hope I have provided enough details, any help would be greatly appreciated. 希望我提供了足够的细节,我们将不胜感激。

I think you want something like 我想你想要类似的东西

function returnVal(itemId, onComplete){
    var data = getValueFromDatabase();
    onComplete(data);
}

updateBtn.onclick = function(e) {
    if(action==1) {
        returnVal(itemID, function(data){
            // Do something with returned value i.e. 'data'
        });
    }
}

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

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