In my project, I want to pass a variable from C# to Javascript, but i am fail :(



public partial class partpart: WebPart
       string str= string.Empty;
        protected void Page_Load(object sender, EventArgs e)
            str = "dog";



$(document).ready(function () {
        var jsStr= '<%=str%>';

What is the best way to pass variable (include string array) from C# in SharePoint web part?

  • 2
    You can use hidden field. Store value using C# code and access that value in javascript function using it's id. – Dikesh Gandhi Oct 27 '16 at 6:08
  • @DikeshGandhi so, using hidden field is the best way to pass variable in web part? – king yau Oct 27 '16 at 6:38
  • Yes. You can use this. Otherwise you can get and set custom webpart properties also. – Dikesh Gandhi Oct 27 '16 at 6:39

Since you are developing a web part, follow the article Creating a Web Part with Client-side Script that describes how to embed JavaScript code from server side code.

In case of array you could utilize ClientScriptManager.RegisterArrayDeclaration Method (String, String) that:

Registers a JavaScript array declaration with the Page object using an array name and array value.

Here is an example:

public class MyWebPart : WebPart

      public MyWebPart()
            this.PreRender += new EventHandler(MyWebPart_PreRender);

      private void MyWebPart_PreRender(object sender , System.EventArgs e )
           String arrName = "cities";
           String arrValue = "\"London\", \"Berlin\", \"Paris\"";
           ClientScriptManager cs = Page.ClientScript;
           // Register the array with the Page class.
           cs.RegisterArrayDeclaration(arrName, arrValue);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.