【问题标题】:DotNet Core calling method via onscreen buttonDotNet Core 通过屏幕按钮调用方法
【发布时间】:2018-11-14 16:08:36
【问题描述】:

在我的 DotNet Core 应用程序中,我设置了一个按钮,其中包含一些 JavaScript,用于我的 OnClick 事件。它看起来像这样:

<div>
    @(Html.DevExtreme().Button()
                             .Text("Press me")
                             .Type(ButtonType.Normal)
                             .Width(90)
                             .OnClick("notify")
    )
</div>

<script>
     function notify() {
        console.log("pressed");

       // ModifiedDuration.AdjustmentScreen_Netting.Csharp.RunBatch();
      //  var a = '<%=RunBatch()%>';
    }
</script>

注释掉的行是我尝试调用的目标方法,但都没有工作。我要调用的底层方法是这样的:

public void RunBatch()
{
    Console.WriteLine("Re-running batch");
    TestOutput print= new TestOutput ();
    print.TestMethod();
 }

那么,TestMethod 做了什么:

public void ProcessAdjustedBatch()
{
    Console.WriteLine("I have been called from the datagrid!!!!");
}

所以在我按下按钮后,我希望看到以下日志消息:

  • 按下
  • 重新运行批处理
  • 我已从数据网格中调用!!!!

但我在开发日志中看到的只是Pressed。我怎样才能达到我的预期输出?

【问题讨论】:

  • function notify() 在客户端进行评估,但我认为 public void RunBatch() 是您后端的一部分。因此浏览器不能使用函数RunBatch。您可以为此方法公开一个 HTTP 接口并通过 HTTP 调用它
  • 这是两个不同的部分。第一个是写入浏览器日志,第二个是写入控制台。您正在混淆客户端和服务器。

标签: javascript c# asp.net-mvc .net-core devextreme


【解决方案1】:

Console.WriteLine() 永远不会显示在客户端的浏览器中,因为它在服务器端运行并在服务器的控制台窗口中打开。如果您想在即时输出窗口中看到调试消息,则必须使用Debug.WriteLine()

还要注意var a = '&lt;%=RunBatch()%&gt;'只在ASPX页面内执行,它不能在使用@{ ... }作为代码段的Razor中执行,并且两种调试方法都是服务器端方法。

如果您想在浏览器控制台中使用console.log() 显示服务器端调试消息,您需要创建一个控制器操作来执行具有string 返回类型的两种方法,然后在notify() 函数中使用AJAX 来输出success 部分中的结果。

这是一个简单的例子:

控制器动作

public IActionResult GetMessages()
{
    var messages = new StringBuilder();

    messages.Append(RunBatch());
    messages.Append("\n"); // use newline to separate messages from different methods
    messages.Append(ProcessAdjustedBatch());

    return Json(messages.ToString(), JsonRequestBehavior.AllowGet);
}

调试方法

public static string RunBatch()
{
    string batch = "Re-running batch";
    Debug.WriteLine(batch);

    TestOutput print = new TestOutput();
    print.TestMethod();

    return batch;
}

public static string ProcessAdjustedBatch()
{
    return "I have been called from the datagrid!!!!";
}

查看(脚本标签)

<script>
function notify() {
   console.log("pressed");

   $.ajax({
       type: 'GET',
       url: '@Url.Action("GetMessages", "ControllerName")',
       dataType: 'json',
       success: function (result) {
           console.log(result);
       }
   });
}
</script>

现在控制台输出应该是这样的:

pressed
Re-running batch
I have been called from the datagrid!!!!

现场示例:.NET Fiddle

相关问题:

Where does Console.WriteLine go in ASP.NET?

Asp.net mvc Console.WriteLine to browser

How to use Console.WriteLine in ASP.Net MVC 3

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多