简体   繁体   English

C#:如何在Javascript中使用全局变量

[英]C#: How to using global variable with Javascript

everyone! 大家! I'm learning ASP.NET MVC and have some question. 我正在学习ASP.NET MVC,并且有一些问题。 My problem is Passing Data from View to Controller. 我的问题是将数据从视图传递到控制器。

This my Code: 这是我的代码:

@{
    string listID = "";
}

and I try to use this variable: 我尝试使用此变量:

function SubmitDelete() {
   var listId = "";        
   var x = document.getElementsByName("IsCheck");
   for (var i = 0; i < x.length; i++) {
     if (x[i].checked == true) {
        listId += x[i].value + ", ";
     };
   }
   @listID = listId;
   return listId;
}

Finalize, I want to pass @listID to Controller: 完成后,我想将@listID传递给Controller:

@using (Html.BeginForm("DeleteChecked", "Category", new { listID }, FormMethod.Post)){ }

It is simple problem about multi delete with checkbox. 这是关于带有复选框的多删除的简单问题。 Help me, please. 请帮帮我。

You cannot pass a javascript variable to your controller. 您无法将javascript变量传递给控制器​​。

But you can post it as part form data with the help of hidden field. 但是您可以在隐藏字段的帮助下将其作为表单数据发布。

Better add a hidden field and set it in a Javascript and post 最好添加一个隐藏字段并将其设置为Javascript并发布

@using (Html.BeginForm("DeleteChecked", "Category", FormMethod.Post)){ 

 Html.HiddenFieldFor(m=>m.MyList, new {@id="my-list-data"})

 ..other controls and your submit button

}

In a Javascript 用JavaScript

function SubmitDelete() {
   var listId = "";        
   var x = document.getElementsByName("IsCheck");
   for (var i = 0; i < x.length; i++) {
     if (x[i].checked == true) {
        listId += x[i].value + ", ";
     };
   }
   $('#my-list-data').val(listId);

}

You cannot do that. 你不能这样做。
The aspx\\ascx\\cshtml etc. page is built in the server side while the js is computed on the client's side. aspx \\ ascx \\ cshtml等页面是在服务器端构建的,而js是在客户端计算的。
You can add C# string to js functions but they will be hard coded when they get to the client. 您可以将C#字符串添加到js函数中,但是当它们到达客户端时,它们将被硬编码。
All the C# expression are evaluated before they get to the client and before the js is computed. 在所有C#表达式到达客户端之前以及在计算js之前,都要对它们进行评估。

Here's an example: This is what you see on the aspx\\ascx\\cshtml file. 这是一个示例:这是您在aspx \\ ascx \\ cshtml文件上看到的内容。

<%
string str = 'test';
%>
function jsFunc(){
var myVar = '<%=str%>';
}

This is what the client gets: 这是客户得到的:

function jsFunc(){
var myVar = 'test';
}

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

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