0

I am trying to pass a C# array to JQuery Function as a Parameter.

My C# Code to call the function is:

//Create an Array from filtered DataTable Column
    var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r.Field<string>("GatePassID")).ToArray<string>(); 


  //Pass Array to JQuery function                 
                Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type='text/javascript' >FillGatePassIDSmartBox("+GatepassIDs+");</script>", false);

Jquery Script:

<script type="text/javascript" >
function FillGatePassIDSmartBox(GatepassIDs) {        

        $('#<%=txt_gatepassID.ClientID%>').autocomplete({
            source: GatepassIDs
    });
}
</script>

The Problem is it is passing System.String[] from C# call instead of passing Array values.

Please help

3 Answers 3

2

Instead of passing your array as a parameter directly from C#, send you array as a variable to your JavaScript. Then you can send it as a parameter to your function:

  var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r.Field<string>("GatePassID")).ToArray<string>();

  StringBuilder sb = new StringBuilder();
  sb.Append("<script>");
  sb.Append("var yourGatePassIDArray= new Array;");
  foreach(string str in GatepassIDs)
  {
    sb.Append("yourGatePassIDArray.push('" + str + "');");
  }
 sb.Append("FillGatePassIDSmartBox(yourGatePassIDArray)");
  sb.Append("</script>");

  Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", sb.ToString());

And then use this in your JavaScript as:

function FillGatePassIDSmartBox(yourGatePassIDArray) {        

        $('#<%=txt_gatepassID.ClientID%>').autocomplete({
            source: yourGatePassIDArray
    });

You would have to declare your array at a global context.

Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend using the Newtonsoft.Json NuGet package, as it makes handling JSON trivial. You could do the following:

var jsonArray = JsonConvert.SerializeObject(GatepassIDs);
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type='text/javascript' >FillGatePassIDSmartBox("+ jsonArray +");</script>", false);

3 Comments

then how will they be accessed in Jquery method?
@AlinaAnjum Jquery method FillGatePassIDSmartBox param will get the string array.
I am working on SharePoint, Hence there are some limitations. can we achieve the same without using JSON?
0

I would recommend this.

var jarr = JsonConvert.SerializeObject(GatepassIDs);

Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "FillGatePassIDSmartBox("+ jarr +");", false);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.