In this artilce, I have explain how to create a web method for get array of string in c# and how to use it.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Web-Method.aspx.cs" Inherits="Tutorials.Web_Method" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
getArrayOfString();
function getArrayOfString() {
var days = [];
$.ajax({
type: "POST",
url: "Web-Method.aspx/getArrayOfString",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function onSuccess(response) {
days = response.d;
var htmlContent = "";
for (var i = 0; i < 7; i++) {
htmlContent += " " + days[i] + "<br>";
}
$("#Days").html(htmlContent);
},
failure: function (response) {
alert(response.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Days">
</div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Web-Method.aspx.cs" Inherits="Tutorials.Web_Method" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
getArrayOfString();
function getArrayOfString() {
var days = [];
$.ajax({
type: "POST",
url: "Web-Method.aspx/getArrayOfString",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function onSuccess(response) {
days = response.d;
var htmlContent = "";
for (var i = 0; i < 7; i++) {
htmlContent += " " + days[i] + "<br>";
}
$("#Days").html(htmlContent);
},
failure: function (response) {
alert(response.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Days">
</div>
</form>
</body>
</html>
C# Code
using System;
namespace Tutorials
{
public partial class Web_Method : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string[] getArrayOfString()
{
string[] days = new string[7];
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuseday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
return days;
}
}
}
Output: