Home > Back-end >  How can I pass JS arrays to C# webforms?
How can I pass JS arrays to C# webforms?

Time:01-05

<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!

CodePudding user response:

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:

 <div>
        <input id="HiddenField" type="hidden" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClientClick="AssignValue()"  Text="Button"
            onclick="Button1_Click1" />
    </div>

     <script>
        function AssignValue() {
        var array1 = ["Saab", "Volvo", "BMW"];
        document.getElementById("HiddenField").value = array1;
    }
</script>

And you can read HiddenField in method, something like this:

    protected void Button1_Click1(object sender, EventArgs e)
    {

            for (int i = 0; i < HiddenField.Value.Length; i  ){
           Response.Write(HiddenField.Value[i]   "<br>");}
    }

This is just a Sample code to give you an idea.

CodePudding user response:

There are several ways to do it. But i prefer one like this:

Set your form's onsubmit attribute a js method:

<form id="myForm" ... onsubmit="serializeArray();">
... 
<script>
    function serializeArray() {
        let hdn = document.createElement('input');
        hdn.type = 'hidden';
        hdn.name = 'array1'; //Name property is important. Because you will use this value at your c# code to get value of this array
        hdn.value = JSON.stringify(array1);
        document.getElementById('myForm').appendChild(hdn);
    } 
</script>

Then on your server side you can get this variable using Request.Form. For example (using Newtonsoft.Json):

var array1 = JsonConvert.DeserializeObject<YourArrayType>(Request.Form["array1"]);
  • Related