简体   繁体   English

如何在 static 方法 c# 中为 asp.net 控件 ID 赋值

[英]how to assign a value to asp.net control id in static method c#

Can we assign a value to asp.net control using id in static method?我们可以使用 static 方法中的 id 为 asp.net 控件分配一个值吗?

I know by using this below code we can get control id value我知道通过使用下面的代码,我们可以获得控制 id 值

Page page = (Page)HttpContext.Current.Handler;
TextBox TextBox1 = (TextBox)page.FindControl("autotrade_lotsizeid");
string ddd = TextBox1.Text;

But my question is can we assign a default value to asp.net control id in runtime when the page is loaded.但我的问题是我们可以在加载页面时在运行时为 asp.net 控件 ID 分配一个默认值。 below is my sample code下面是我的示例代码

[WebMethod]
public static void GetLotSizeVal(string symbol, string expdate)
        {
            try
            {
                string lotsizevalres = GetAPIResponse("https://xxxx.com/funs.aspx?otype=analyse_qty&symbol=" + symbol + "&expdate=" + expdate + "");
                var lotsizeval = JsonConvert.DeserializeObject<List<LotSizeValRes>>(lotsizevalres);

                if (!ReferenceEquals(lotsizeval,null) && lotsizeval.Count>0)
                {
                    for (int i = 0; i < lotsizeval.Count; i++)
                    {
                        //Getting Error here (But I wat to add default value)
                        autotrade_lotsizeid.Text = Convert.ToString(lotsizeval[i].LotSizeVal);

                        //Error not coming but unable to assigning the value to that control id
                        //Page page = (Page)HttpContext.Current.Handler;
                        //TextBox TextBox1 = (TextBox)page.FindControl("autotrade_lotsizeid");
                        //string ddd = TextBox1.Text;

                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
       
        }

Suggest me how to assign a default value.建议我如何分配默认值。

No, you can't.不,你不能。 so a static method CAN modify controls if you say pass the control in question as a parameter.因此,如果您说将有问题的控件作为参数传递,则 static 方法可以修改控件。

However, a web method on the page is ALSO static, but the controls on the page do not exist.但是,页面上的一个 web 方法是 ALSO static,但是页面上的控件不存在。

Remember, the web server is NOT just for YOUR web page.请记住,web 服务器不仅适用于您的 web 页面。 Many web pages from all users can be posted to the web server.来自所有用户的许多 web 页面都可以发布到 web 服务器。

When you post back a page, a "instance" of your class page is created.当您回发页面时,会创建 class 页面的“实例”。 Then code behind can run and modify controls on the page.然后后面的代码可以运行和修改页面上的控件。 The page is then sent back to client side, and then the page class is disposed (removed from memory and existence in the computer).然后页面被发送回客户端,然后页面 class 被处理(从 memory 中删除并存在于计算机中)。

Think of a post-back much like a subroutine call.把回发想象成一个子程序调用。 You call the routine, code runs and when you exit the sub, then all values and variables in that sub go out of scope, and don't exist anymore.您调用例程,代码运行,当您退出子程序时,该子程序 go 中的所有值和变量从 scope 中消失,并且不再存在。 A web page "round trip" from post-back, then code behind runs, then page is send back to your desktop.来自回发的 web 页面“往返”,然后代码后面运行,然后页面被发送回您的桌面。 Once the page is sent back to your desktop, the code and values and variables on the server side now don't exist in memory - they are out of scope.将页面发送回桌面后,服务器端的代码、值和变量现在不存在于 memory 中 - 它们不在 scope 中。

You have this - the web page is sitting on your desktop你有这个 - web 页面位于您的桌面上

在此处输入图像描述

Note how the page is sitting CLIENT side.请注意页面是如何坐在客户端一侧的。 On the server, THERE IS NOT a instance of that page class.在服务器上,没有该页面 class 的实例。

NOTE VERY careful here - the web page is ON CLIENT computer - it is NOT existing at all on the web server side.注意这里非常小心 - web 页面在客户端计算机上 - 它在 web 服务器端根本不存在。

You do not have this:你没有这个:

在此处输入图像描述

And you DO NOT HAVE this either:你也没有这个:

在此处输入图像描述

so, if you click a button on your web page, then a post-back starts (the so called page life cycle or round trip).因此,如果您单击 web 页面上的按钮,则会开始回发(所谓的页面生命周期或往返)。

在此处输入图像描述

So, your web page is posted to the server, and THEN a instance of the page class is created.因此,您的 web 页面已发布到服务器,然后创建页面 class 的实例。

在此处输入图像描述

o NOW your page is sitting on the server. o 现在您的页面位于服务器上。

NOW a instance of the page class is created, and your code behind starts running.现在创建了页面 class 的实例,您的代码开始运行。

Your code behind can modify controls (even set visible settings etc.), but the page is NOT interacting with the user - ONLY code can MODIFY the web page.您后面的代码可以修改控件(甚至设置可见设置等),但页面不与用户交互 - 只有代码可以修改 web 页面。 The user does NOT see the changes your code has made.用户看不到您的代码所做的更改。

After code behind runs (and only after), then web page is sent back to the client side, and the server side class instance and code is TOSSED OUT - DOES NOT exist.!!在后面的代码运行之后(并且仅在之后),然后 web 页面被发送回客户端,服务器端 class 实例和代码被丢弃 - 不存在。!! Goes out scope - disposed.熄灭 scope - 已处置。

You now have this:你现在有这个:

在此处输入图像描述

Now the web page is back on your desktop, and THEN and ONLY then do you see the changes that your code behind made.现在 web 页面重新出现在您的桌面上,然后您才能看到您的代码所做的更改。

The page class on the server is now tossed out - disposed, now destroyed.服务器上的页面 class 现在已被丢弃 - 已处理,现在已销毁。

After all the web server is NOT JUST for you, but is waiting to process any old web page from any user.毕竟 web 服务器不只是为您服务,而是等待处理来自任何用户的任何旧 web 页面。

So, on the server side, your web page class and variable(s) are now disposed, don't exist, and the web server is waiting for ANY user - not just you to post back a page.因此,在服务器端,您的 web 页面 class 和变量现在已处理,不存在,并且 web 服务器正在等待任何用户 - 而不仅仅是一个页面。

So, if you do a post back, then static methods can be called from your code behind web page class.因此,如果您进行回发,则可以从 web 页面 class 后面的代码调用 static 方法。

But, if you do NOT do a post-back, then the "instance" of that page class does not exist in memory, BUT MORE important nor does the page data and controls exist!!!但是,如果您不执行回发,则 memory 中不存在该页面 class 的“实例”,但更重要的是,页面数据和控件也不存在!!!

So, when you use a web method, it has to be static, since the whole page class and variables don't exist, are not created, nor are the controls and values post-back to the server.因此,当您使用 web 方法时,它必须是 static,因为整个页面 class 和变量不存在,不创建回发到服务器,也不创建控件和值。 The values of text box etc. are STILL on your desktop!!!文本框等的值仍然在您的桌面上!!!

Since the web page is just sitting on your desktop, then the server side static methods don't have a copy of your web page on the server in which to modify those controls.由于 web 页面仅位于您的桌面上,因此服务器端 static 方法在服务器上没有您的 web 页面的副本以修改这些控件。 (they are still sitting on your desktop). (他们仍然坐在您的桌面上)。

So, you can certainly have a static method run code, and if you pass it some controls, it can operate on those values, and then return the values, at which time your client side code can then up date the text box.因此,您当然可以让 static 方法运行代码,如果您向它传递一些控件,它可以对这些值进行操作,然后返回值,此时您的客户端代码可以更新文本框。

I mean, lets drop in a firstname text box, a lastname text box, and a full name text box.我的意思是,让我们放入名字文本框、姓氏文本框和全名文本框。

Then a button.然后是一个按钮。 You are to enter the first name, the last name, and when we click on the button, the full name text box will be filled out.您要输入名字,姓氏,当我们点击按钮时,将填写全名文本框。

So, with 100% server side code - no web method, then say this markup:因此,使用 100% 的服务器端代码 - 没有 web 方法,然后说这个标记:

            Enter First Name: 
            <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            Enter First Name: 
            <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            <asp:Button ID="cmdCombine" runat="server" Text="combine first and last" 
                CssClass="btn" OnClick="cmdCombine_Click"  />

            <br />
            Full name result: 
            <asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static" Width="336px"></asp:TextBox>

And the code behind is this:后面的代码是这样的:

    protected void cmdCombine_Click(object sender, EventArgs e)
    {
        txtFullName.Text = txtFirst.Text + " " + txtLast.Text;
    }

So, we now get this example:所以,我们现在得到这个例子:

在此处输入图像描述

Ok, now lets do this with a web method.好的,现在让我们使用 web 方法来执行此操作。

So, we add this code to our page:因此,我们将这段代码添加到我们的页面中:

    [WebMethod()]
    public static string CombineName(string FirstName, string LastName)
    {
        string MyResult = "";
        MyResult = FirstName + " " + LastName;
        return MyResult;
    }

So, we now have the above code on the web page - but it is AND MUST be static, since without a post-back the web page is STILL SITTING on YOUR desktop - the page class does NOT exist server side. So, we now have the above code on the web page - but it is AND MUST be static, since without a post-back the web page is STILL SITTING on YOUR desktop - the page class does NOT exist server side. (and controls (their value) does not exist at this point in time)). (并且控件(它们的值)此时不存在))。

So, to make the web method change things on the page?那么,要让 web 方法更改页面上的内容? It cannot, since the web page is not on the server - but on your desktop..!它不能,因为 web 页面不在服务器上 - 但在您的桌面上..! (it would be cool if my code could reach out to your computer - I would grab all your banking information!!!).. (如果我的代码可以访问您的计算机,那就太酷了——我会获取您所有的银行信息!!!)..

So, while you can call a static web method, to modify controls on the current web page???因此,虽然您可以调用 static web 方法来修改当前 web 页面上的控件???

Then your code to call the web method will have to pass the first name, last name, return the value and then CLIENT SIDE code can update the full name text box.然后你的代码调用 web 方法将必须传递名字,姓氏,返回值然后 CLIENT SIDE 代码可以更新全名文本框。

Say, like this:说,像这样:

        <asp:Button ID="cmdAjaxTest" runat="server" Text="Web method button"
            OnClientClick="mycombine();return false;"/>


        <script>

            function mycombine() {

                MyFirstName = $("#txtFirst").val()
                MyLastName = $("#txtLast").val()
                
                $.ajax({
                    type: "POST",
                    url: "AjaxTest2.aspx/CombineName",
                    data: JSON.stringify({ FirstName: MyFirstName, LastName: MyLastName}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                        success: function (myresult) {
                        // put result of method call into txtResult
                        // ajax data is ALWAYS ".d" - its a asp.net thing!!!
                        $("#txtFullName").val(myresult.d)
                    },
                    error: function (xhr, status, error) {
                        var errorMessage = xhr.status + ': ' + xhr.statusText
                        alert('Error - ' + errorMessage)
                    }
                });
            }
        </script>

so, now the above ajax + web method does the same thing and has the same result.所以,现在上面的 ajax + web 方法做同样的事情并具有相同的结果。 We took first name, last name, and called a page static web method, that static method combined the first and last, and return the value.我们取名,姓,调用一个页面 static web 方法,即 static 方法结合了第一个和最后一个,并返回值。

But that static class can't change controls on the web page server side, since no copy of the web page, or the page class exists on the server. But that static class can't change controls on the web page server side, since no copy of the web page, or the page class exists on the server.

Once that standard classic round trip is complete after a post-back, then the variables and page class server side are disposed, tossed out, and the web server is waiting for ANY user, not just you to post back a web page to start that "page life cycle", or so called round trip.一旦标准的经典往返在回发后完成,那么变量和页面 class 服务器端将被丢弃,web 服务器正在等待任何用户,而不仅仅是您将 Z2567A5EC9EC9305EB7AC2C94 页面回发到 start0305EB189DZ84 “页面生命周期”,或者所谓的往返。

So can a static method modify a control on your web page?那么 static 方法可以修改 web 页面上的控件吗? Sure, as long as you pass that value.当然,只要您传递该值。

So, on a button click, I can do this:所以,点击按钮,我可以这样做:

 General.MyChangeTextBox(TextBox1,"Hello")

That static class can now modify the TextBox1, since we passed the object TextBox1 from our current code behind and page object class. That static class can now modify the TextBox1, since we passed the object TextBox1 from our current code behind and page object class.

but, a web method can't do the above, and it not because the web method is static, the issue is that you don't have a existing page class in memory that exists from which to pass values and things to that static method. but, a web method can't do the above, and it not because the web method is static, the issue is that you don't have a existing page class in memory that exists from which to pass values and things to that static method .

As a result, you can call web methods, and RETURN values from that web method, and then the CLIENT side code is free to modify the controls on the web page.因此,您可以调用 web 方法,并从该 web 方法返回值,然后 CLIENT 端代码可以自由修改 web 页面上的控件。

You can't modify the controls server side, since no server side copy of the web page exists at that point in time - it is still sitting on your desktop!!您无法修改控制服务器端,因为在那个时间点不存在 web 页面的服务器端副本 - 它仍然位于您的桌面上!

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

相关问题 如何在ASP.NET C#中为按钮分配动态ID - How to assign dynamic id to button in asp.net c# 如何获取控件值表单控件ID asp.net C#? - How to get Control Value Form Control ID asp.net C#? 如何为 a.txt 文件中添加的每个行分配一个 ID 值(ASP.NET MVC / C#) - How to assign an ID value to each added row in a .txt file (ASP.NET MVC / C#) 如何使用 C# asp.net 在静态方法中查找 Div id - How to find Div id inside Static method using C# asp.net c#如何在静态Web方法中获取asp.net文本框值? - c# how to get asp.net textbox value inside static web method? ASP.NET,C#,如何动态识别用户控件的属性或方法并为其添加价值? - ASP.NET, C#, How to dynamically identify the properties or method of a user control and add value to them? 如何在ASP.NET中获取DateRangePicker控件值(C#) - How to get DateRangePicker control value in ASP.NET (C#) asp.net中静态或共享方法中的访问控制值 - Access Control value in static or shared Method in asp.net 如何在ASP.Net C#中将连接字符串分配给ChangePassword控件 - How to Assign Connection String to ChangePassword control in ASP.Net c# 如何使用C#将位图分配给ASP.NET中的Image控件? - How can I assign a bitmap to a Image control in asp.net using c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM