Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, January 8, 2014

ASP.net page methods with argument passing

Related to ASP.net, in some cases we need to call server side methods using client side javascript functions with Ajax. The most efficient way to implement that facility is called page methods. I have found a very successful Blog by related to implementing this page methods. This blog is a small extension of the above mentioned blog.
In practical situations we may need to pass parameters to the server-side from client-side. How can we do that using the same example described in the above mentioned blog.

Let's assume that we need to add two numbers. The numbers are going to input by the user via a text input in HTML.Addition will be done in server-side (by a C# method in ASP.net) after we click a button. (Ajax technology will be used)

  • Define 2 text inputs in HTML

<input id="Text1" type="text" />
<input id="Text2" type="text" />

  • Define a HTML button and calls to a function in the onclick event

<input id="Button1" type="button" value="button" onclick="inputNum()"/>

  • Define a ASP.net script manager in client-side (just drag and drop the controller from the tool box)

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" EnablePartialRendering="true"> </asp:ScriptManager>

  • Define following functions in the client-side using Javascript. (Here I use an array to pass the two numbers as arguments to the server-side method)

function inputNum() {

            var nums = new Array();
            nums[0] = document.getElementById("Text1").value;
            nums[1] = document.getElementById("Text2").value;
            GetInputNumFromServer(nums);
        }

        function GetInputNumFromServer(numsArray) {
            PageMethods.GetSum(numsArray, OnSuccess, OnError);

            return false;
        }

        function OnSuccess(response) {
            alert(response);
        }
        function OnError(error) {
            alert(error);
        }



  • Define the C# method in the server-side. (You have to use the System.Web.Services reference)

 [WebMethod]
        public static int GetSum(int[] arr)
        {
            return arr[0]+arr[1];
        }



That's All.

Wednesday, June 26, 2013

Infinite Array Problem In C#.net

You can't define C#.net arrays with an infinite array length. You must have to provide a length for the array. But there is a solution to fulfill the need of infinite arrays in C#.net.
We call it as List.

We can define a C#.net array like below,
Syntax:-
List<data_type>name_for_list=new List<data_type>();
eg:-
List<char>plainChar=new List<char>();

We can feed data to the list like below,
Syntax:- 
list_name.Add(value_needed_to_add);
eg :-
plainChar.Add('C');

We can retrieve elements from the list like below,
Syntax:- 
list_name[index_of_the_element];
eg:-
plainChar[3];