Qus:    How do I pass a text box value via a function in ASP.NET and C#?
Apr 20, 2021 11:37 1 Answers Views: 65 DIVYA
Prev Next
Answers (1)
SHIVA Apr 21, 2021 08:42
Answer:   For retreiving a value from TextBox do this:
Suppose you have a textbox tag something like this in your .aspx file:
1.
Just go in your codebehind, .cs file:
Retreive the textbox value using the .Text property of the server side textbox control
1. private void button_Click(object sender, EventArgs e)
2. {
3. string textBoxValue = someTextBox.Text.ToString();
4. SomeFunction(textBoxValue);
5. }
6. void SomeFuntion(string param)
7. {
8. //Perform your logic here
9. }
2. To set value of ASP textbox using jQuery selectors and jQuery AJAX call:
The Index.aspx file may look something like this:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10. Enter name:
11.
12.
13.
14. Text box to be populated:
15.
16. function submit() {
17. //Set the value you gonna pass
18. var PersonName = "some thing";
19.
20. //encode it in a jQuery Object
21. var dataValue = { "name": PersonName };
22.
23. //Make an jQuery AJAX call to asynchronously load the text box at run time
24. $.ajax({
25. type: "POST",
26. url: "Index.aspx/OnSubmit",
27. data: JSON.stringify(dataValue), //Pass the jQuery Object you created above as a query string parameter so that the server side C# code might process it
28. success: function(data)
29. {
30. $(‘txtBoxToBePopulated’).html(data); //Set the value of that textbox you want to get polulated which has id = txtBoxToBePopulated
31. },
32. error: function (XMLHttpRequest, textStatus, errorThrown) {
33. alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
34. }
35. });
36.
37. }
38.
39.
40.
Your code behind Index.aspx.cs file:
1. using System;
2. using System.Web.Services;
3. using System.Web.UI;
4.
5. namespace TestAspStuff
6. {
7. public partial class _Default : Page
8. {
9. protected void Page_Load(object sender, EventArgs e)
10. {
11. }
12.
13.
14. //You have to decorate your C# method with WebMethod attribute so that you may use it in the jQuery AJAX call
15.
16. [WebMethod]
17. public static string OnSubmit(string name)
18. {
19. return "some thing";
20. }
21. }
22. }
If you face any doubt, go through the following footnotes:
• jQuery Selectors -> jQuery Selectors
• jQuery AJAX call -> jQuery AJAX Methods
• JSON.Stringify() -> JSON.stringify()
• C# [WebMethod] attribute -> Calling an ASP.NET C# Method (Web Method) Using JavaScript (http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/)

Post Your Answer
Guest User

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect