<head runat="server">
<title></title>
<script>
const array1 = ["Saab", "Volvo", "BMW"];
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" />
</div>
</form>
</body>
public partial class JSPassWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
for (int i = 0; i < array1.Length; i++)
Response.Write(array1[i] + "<br>");
}
}
How can I do to pass the JS array to C#? (I don’t want to use ajax if possible)
Any help would be greatly appreciated, thanks!
2
Answers
You can create one hidden field on the view and pass your array to that field. THen you can access that hidden field’s value inside your method.
Something like this. Change your view to this:
And you can read
HiddenField
in method, something like this:This is just a Sample code to give you an idea.
There are several ways to do it. But i prefer one like this:
Set your form’s
onsubmit
attribute a js method:Then on your server side you can get this variable using
Request.Form
. For example (using Newtonsoft.Json):