how to access c# variable in JavaScript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ankababu
    New Member
    • Feb 2007
    • 1

    how to access c# variable in JavaScript

    I have a simple application in which i want to access a variable of codebehind(.cs) file in javascript so that i can compare its value on client side only instead of going to server side

    thnx in advance , guys help me asap
  • dorinbogdan
    Recognized Expert Contributor
    • Feb 2007
    • 839

    #2
    Try to use an AJAX method.

    Comment

    • tusharg
      New Member
      • Oct 2007
      • 1

      #3
      Originally posted by ankababu
      I have a simple application in which i want to access a variable of codebehind(.cs) file in javascript so that i can compare its value on client side only instead of going to server side

      thnx in advance , guys help me asap

      ----------------------------------------------------

      In .cs file , i create a public string variable [this is class member variable, not in the function] like

      public string m_companyName = "MyCompany" ;


      following function is javscript function, which access .cs file variable in javascript;


      function FeedbackValidat ion()
      {


      alert('<% Response.Write( companyName); %>');


      }


      Thanks & Regards
      Tushar Galankar

      Comment

      • knjsandeepkumar
        New Member
        • Nov 2011
        • 1

        #4
        HI Tuhsar,

        One method you can try is, to send that data to the view page using ViewModel or the Model of Strongly typed page (if it is a strongly type page) and write it in a hidden input type. by doing this, you can access it from java script using Jquery.

        this wil be some thing like..

        in the Controller, where you reutn back data to the view,

        public ActionResult Index(...params ..)
        {
        // controller Logic...
        var viewModel[CompanyName] ="MYCOMPANY" ;

        return View(viewModel)
        }


        and in the view page..in some div..

        <input type="hidden" id="companyName " value="<%=viewM odel[CompanyName]%>" />

        and from the js file, access this using Jquery as,

        var myCompanyName = $("#companyName ").val();

        Comment

        Working...