简体   繁体   English

在后面的代码中将 JS 参数传递给 c# 函数 - .net

[英]Passing JS parameter to c# function in code behind- .net

I am trying to call ac# function from JavaScript but the problem is, I need to pass a JS parameter for the function.我试图从 JavaScript 调用 ac# 函数,但问题是,我需要为该函数传递一个 JS 参数。 How can I do this?我怎样才能做到这一点?

Here's my Js这是我的 Js

 var categoryLists = <%= this.javaSerial.Serialize(this.categoryList) %>;
        function addInput(type, value, name, id, onclick, parentId) {
            var element = document.createElement("input");
            element.type = type;
            element.value = value;
            element.name = name;
            element.id = id;
            element.onclick = onclick;
            element.src = "trash.png";
            element.style.width = "25px";
            element.style.height = "25px";
            element.style.marginBottom = "3%";
            var parent = document.getElementById(parentId);
            
            parent.appendChild(element);
        }

        function addBreak(parentId) {
            var br = document.createElement("br");
            var parent = document.getElementById(parentId);
            parent.appendChild(br);
        }
         
        window.onload = function () {
            alert(this.categoryLists.length);
            for (var j = 0; j < this.categoryLists.length; j++) {
                var temp = "button" + j;
                addInput('image', '', temp, temp, <%=DeleteCategory(%>+categoryLists[j]), 'rightdiv');
                addBreak('rightdiv');
            }
        }

categoryLists[j] is my paramter categoryLists[j] 是我的参数

Here's the c# code这是c#代码

public void DeleteCategory(string category){
}

    public JavaScriptSerializer javaSerial = new JavaScriptSerializer();

Update- I call c# functions this way... <%= function()%> and they work fine.更新 - 我以这种方式调用 c# 函数... <%= function()%> 并且它们工作正常。 Thank you in advance先感谢您

Update- with all the comments, I have tried using ajax or jquery - i am not sure what this is ... now my js looks like this and its broken... are there syntax issues?更新-所有的评论,我试过使用ajax或jquery-我不确定这是什么......现在我的js看起来像这样而且它坏了......是否有语法问题?

 $(function () {
            function addInput(type, value, name, id, onclick, parentId) {
                var element = document.createElement("input");
                element.type = type;
                element.value = value;
                element.name = name;
                element.id = id;
                element.onclick = onclick;
                element.src = "trash.png";
                element.style.width = "25px";
                element.style.height = "28px";
                element.style.marginBottom = "3%";
                var parent = document.getElementById(parentId);

                parent.appendChild(element);
            }

            function addBreak(parentId) {
                var br = document.createElement("br");
                var parent = document.getElementById(parentId);
                parent.appendChild(br);
            }

             for (var j = 0; j < this.categoryLists.length; j++) {
                var temp = "button" + j;
                addInput('image', '', temp, temp, temp, 'rightdiv');
                addBreak('rightdiv');
            }
        });

You have quite a few ways to do this.你有很多方法可以做到这一点。

You can use the cheater approach.您可以使用骗子方法。 Drop in a text box, and a standard button (that will call server side code behind).放入一个文本框和一个标准按钮(将调用服务器端代码)。 (set clientID mode for this button and text box as static). (将此按钮和文本框的 clientID 模式设置为静态)。

<asp:Button ID="btnHidden" runat="server" Text="hidden but"  />
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" ></asp:TextBox>

Ok, now in your js you can go:好的,现在在你的 js 中你可以去:

<script>
   // set the value we want to pass in the hidden text box
   $('#txtHidden').value("abc");
   $('#hiddenButton').click;
<script>

Note: above is jQuery syntax.注意:以上是 jQuery 语法。 You could do this: (pure js no jQuery)你可以这样做:(纯js没有jQuery)

var myvaluetopass = "this is some text to pass as variable";
document.getElementById('<%= TextHiddenBox.ClientID %>').value = myvaluetopass;
document.getElementById('<%= btnHidden.ClientID %>').click();

so you don't have to introduce jQuery here - it can be some "time" and "hassle" to setup + get jQuery working.所以你不必在这里介绍 jQuery - 设置 + 使 jQuery 工作可能需要一些“时间”和“麻烦”。

So, the above will simple click on the hidden button, and the hidden text box will have the value that the code behind can work with.因此,上面将简单地单击隐藏按钮,隐藏文本框将具有后面的代码可以使用的值。 Once you wire up the above?一旦你连接上面?

Then hide the button and the text box like this:然后像这样隐藏按钮和文本框:

<asp:Button ID="btnHidden" runat="server" Text="hidden but"  style="display:none"/>
<asp:TextBox ID="TextHiddenBox" runat="server" ClientIDMode="Static" style="display:none" ></asp:TextBox>

Now, the above is certainly somewhat "klugey".现在,以上肯定有点“笨拙”。 But when you starting out, it can work quite well.但是当你开始时,它可以很好地工作。 So, you set the value of some text box (often hidden), and then with js you FIRE the click event of another button (again often hidden).因此,您设置了一些文本框的值(通常隐藏),然后使用 js 触发另一个按钮的点击事件(再次通常隐藏)。 This now gets you a easy way to run one particular code behind routine, and not have to wire up complex ajax code.这现在为您提供了一种在例程后面运行特定代码的简单方法,而不必连接复杂的 ajax 代码。

The next approach?下一个方法? Well, fire a post back command.好吧,发出回发命令。 This again like the above hidden button trick assumes you need/want a post back here in addition to calling that one routine.这与上面的隐藏按钮技巧一样,假设除了调用该例程外,您还需要/想要回帖。 this approach is somewhat better in that you don't have to drop on the form two hidden controls.这种方法更好一些,因为您不必在窗体上放置两个隐藏控件。

You ALSO need to drop in the script manager for this to work (don't know why).您还需要加入脚本管理器才能使其工作(不知道为什么)。 But you can do this in your code:但是您可以在代码中执行此操作:

     var myvaluetopass = "this is some text to pass as variable";
     __doPostBack("MyCoolEventName", myvaluetopass);

So, the above fires a page post back, and then in the load event, we have this:所以,上面会触发一个页面回发,然后在加载事件中,我们有这个:

 If Request("__EVENTTARGET") = "MyCoolEventName" Then

     Dim str As String = Request("__EVENTARGUMENT")

        Debug.Print("passed value = " & str)
 End If

or as C#或作为 C#

 if (Request("__EVENTTARGET") == "MyCoolEventName")
 {
    string str = Request("__EVENTARGUMENT");
    Debug.Print("passed value = " + str);
 }

So the above are some simple ways.所以以上是一些简单的方法。

The ALL above ideas do cause a full page post-back to run.以上所有想法确实会导致运行整页回发。 Now, if the routine you calling DOES need to set/get/change/deal with/see any control on the page, then of course one does need and want that all important page post back.现在,如果您调用的例程确实需要设置/获取/更改/处理/查看页面上的任何控件,那么当然确实需要并希望所有重要的页面都回传。

Last but not least?最后但并非最不重要的? Well, you can do a ajax call, and that will call a specific routine on your page, pass values (if you want), and ONLY run that one routine.好吧,您可以执行 ajax 调用,这将调用页面上的特定例程,传递值(如果需要),并且仅运行该例程。 This can be VERY nice, it fast, and you do NOT get a full page post back.这可能非常好,速度很快,而且您不会收到整页的帖子。 So, if the routine you need to run does not have to modify, or do much of anything on the web page, then ajax is certainly the best way to go (assuming that the routine you calling does NOT need to modify or change things on the page - since as noted, no page post-back will occur. And if you looking to use that value with code behind and modify things on the page, then you will need a post-back.所以,如果你需要运行的例程不需要修改,或者在网页上做很多事情,那么 ajax 肯定是最好的方法(假设你调用的例程不需要修改或改变页面 - 因为如前所述,不会发生页面回发。如果您希望使用该值与代码隐藏并修改页面上的内容,那么您将需要回发。

But, lets assume you do need to pass one, or do values.但是,让我们假设您确实需要传递一个或执行值。

Well, I suggest jQuery - it just makes the code a bit easier to write.好吧,我建议使用 jQuery - 它只是让代码更容易编写。

So, say in your web page, you have this simple sub, and want to pass two values:因此,假设在您的网页中,您有这个简单的 sub,并且想要传递两个值:

<WebMethod()>
 Public Shared Sub MySimpleSub(MyCoolPassValue As String, Age As Integer)

    Debug.Print("passed string value = " & MyCoolPassValue & vbCrLf & "Age = " & Age.ToString)

 End Sub

or:或者:

[WebMethod()]
public static void MySimpleSub(string MyCoolPassValue, int Age)
{
   Debug.Print("passed string value = " + MyCoolPassValue + Constants.vbCrLf + "Age = " + Age.ToString());
}

So in above, it just a public sub.所以在上面,它只是一个公共子。 (in the code behind for that web page). (在该网页背后的代码中)。 (note the Shared - it HAS to be Static sub - since we calling the page - but don't have the full class object model). (注意共享 - 它必须是静态子 - 因为我们调用页面 - 但没有完整的类对象模型)。 We also need a我们还需要一个

Imports System.Web.Services

Ok, now to call the above as ajax?好的,现在将上面的内容称为ajax?

We get this:我们得到这个:

            var myvaluetopass = "this is some text to pass as variable";
            var age = 23;

            $.ajax({
                type: "POST",
                async: true,
                url: 'OnePicture.aspx/MySimpleSub',
                data: JSON.stringify({MyCoolPassValue: myvaluetopass, Age: age}),
                contentType: "application/json; charset=utf-8",
                datatype: "json"
            }
            );
        }

So in above, we passed two values to the sub in the web form.所以在上面,我们向 web 表单中的 sub 传递了两个值。

The above did assume jQuery.上面确实假设了 jQuery。 I can write it out as pure JavaScript, but the above thus gives;我可以把它写成纯 JavaScript,但上面给出了;

How to pass values - hidden control idea.如何传递值 - 隐藏控制的想法。 Or use __dopostback - this gets rid of the requirement to have a button + hidden text box (and use style="display:none" to hide the button and text box above (if you using that idea, and get it working).或者使用 __dopostback - 这摆脱了按钮 + 隐藏文本框的要求(并使用 style="display:none" 隐藏上面的按钮和文本框(如果你使用这个想法,并让它工作)。

As noted, I don't know why, but you have to drop a Scriptmanager into the page if you going to use dopostback.如前所述,我不知道为什么,但是如果您要使用 dopostback,则必须将 Scriptmanager 放入页面中。 (or pass a valid control ref as the first parameter - it will just to your button code behind routine). (或将有效的控件引用作为第一个参数传递 - 它只会传递给您的按钮代码隐藏例程)。 But, my dopostback example simple gets/grabs the value in teh page load event (event args).但是,我的 dopostback 示例简单地获取/获取页面加载事件(事件参数)中的值。

And then last but not least, we pass a value direction to a web method (sub) in that page - this is a ajax call, and just keep VERY much in mind that the code for this routine has to work without assuming that a page post-back occurred (compared to all previous examples that assumed you need a post back).最后但并非最不重要的一点是,我们将值方向传递给该页面中的 Web 方法(子)——这是一个 ajax 调用,并且要非常牢记,此例程的代码必须在不假设页面的情况下工作发生回发(与假设您需要回发的所有先前示例相比)。

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

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