【问题标题】:.net Core Using razor function in Javascript.net Core 在 Javascript 中使用 razor 函数
【发布时间】:2020-12-30 07:11:58
【问题描述】:

您好,我必须在 js 中使用 c# 代码。我的 js 和 .cshtml 页面是分开的。我在 .cshtml 页面中编写了一个函数,并在 .js 文件中调用它。

在Js文件中

DataList.forEach(function (item) {
     ...
 var users = GetUsers(item.AssignedUsers);

到这里

索引.cshtml

  <script>
    
        function GetUsers(userIdList) {
    //it logs it, i can get theese values from here
            console.log("userIdList");
            console.log(userIdList);
              @{ // but in here it says userIdList does not exist in current content
//also tryed this.userIdList
                  var users = userIdList.Split(",");
                  foreach (var item in users)
                  {
                      var user = _Manager.FindByIdAsync(item.UserId).Result;
    
                  }
              }
    
          }
    </script>

【问题讨论】:

  • 谁能帮帮我,我在c#razor中无法访问userIdList函数参数
  • in here it says userIdList does not exist ...是的,因为它是 JavaScript 变量而不是 c# 变量。您不能像那样将语言混合在一起。它们在不同的时间和不同的地方执行(JavaScript 的浏览器,c# 的服务器)。如果您需要根据 JavaScript 生成的值调用一些 c#,那么显而易见的做法是向服务器发出 AJAX 请求,然后服务器可以执行 c# 并返回响应
  • 阅读以下内容可能对您有所帮助:stackoverflow.com/questions/13840429/…(很多示例都是关于 PHP,但同样的概念也适用于 asp.net 或任何其他服务器端语言)
  • 我明白,我也想过 ajax,但它可能会花费很多。这是一个解决方案,但我必须设置简单的数据。我也在循环播放它
  • 您可以在一个 Ajax 请求中将整个列表发送到服务器并在那里循环,然后在响应中返回一个列表。不需要多个效率低下的 Ajax 请求

标签: javascript c# asp.net-core


【解决方案1】:

您可以将列表从 ajax 传递给控制器​​操作,然后操作返回您想要的列表。 这是一个演示:

<button onclick="sendData()">
    send
</button>
<script>
function sendData() {
                //here is a sample list
                var list = [];
                var user1 = {};
                user1.Id = 1;
                user1.Name = "u1";
                list.push(user1);
                var user2 = {};
                user2.Id = 2;
                user2.Name = "u2";
                list.push(user2);
                $.ajax({
                type: "POST",
                url: '@Url.Action("SendData", "Test")',
                contentType: "application/json",
                data: JSON.stringify(list),
                }).done(function (data) {
                    console.log(data);
                     //the data is you want
                });
            }
</script>

行动:

public List<User> SendData([FromBody]List<User> list) {
            //you can do something and return a list you want here
            return list;
        }

用户:

public class User {
        public int Id { get; set; }
        public string Name { get; set; }

    }

结果:

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2022-12-11
    • 2021-11-18
    • 2021-03-08
    • 2021-05-29
    • 2020-03-25
    • 2018-09-24
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多