如何从脚本中的 razor 页面调用 C# 函数?

时间:2021-06-30 20:56:16

标签: c# asp.net-core razor-pages

enter image description here 每次我运行它时,它都会在我按下按钮之前转到 c 函数。

1 个答案:

答案 0 :(得分:1)

如果你想在脚本中调用C#function,可以尝试使用ajax来调用controller action,在action中调用c#函数,这里有一个demo:

public IActionResult TestFunction() {
            return View();
        }
        public List<string> CallFunction()
        {
            return function();
        }
        public List<string> function()
        {
            return new List<string> { "1", "2", "3" };
        }

查看:

<input id="data" />
<button onclick="CallFunction()">CallFunction</button>
<script>
    function CallFunction() {
        $.ajax({
                type: "GET",
                url: 'CallFunction',
        }).done(function (result) {
            $("#data").val(result.toString());
            });
    }
</script>

结果: enter image description here