简体   繁体   English

如何将JS数据从脚本文件传递到C#方法

[英]How to pass JS data from script file to C# method

I've been wracking my brain over this problem for a while. 一段时间以来,我一直在为这个问题而绞尽脑汁。 How can I invoke a JS function and retrieve the data to be used within a C# method? 如何调用JS函数并检索要在C#方法中使用的数据?

Should I be using ViewBag in this example? 在此示例中我应该使用ViewBag吗?

.cshtml .cshtml

<script>
  function somefunction(str)
   {
      //use str within Index() method
      return str;
   }
</script>

Controller 调节器

   public IActionResult Index()
        {
            //use the data within this method
            return View();
        } 

Have you tried this 你尝试过这个吗

In javascript function: 在javascript函数中:

//Do your action
window.location.href = '@Url.Action("Index", new { value = 1})';

and modify the Index Action to accept parameter like this: 并修改索引操作以接受如下参数:

public ActionResult Index(int value)

As your Index returns a View, window.location.href will basically redirect to Index action. 当您的索引返回一个View时,window.location.href基本上将重定向到Index操作。

You can also create an url using string concatenation in javascript and use that url to redirect. 您还可以使用javascript中的字符串连接创建网址,并使用该网址进行重定向。

In my case the @Url.Action converts to this URL : '/Home/Index?value=1'. 在我的情况下,@ Url.Action转换为以下URL:“ / Home / Index?value = 1”。

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

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