Ibraheem Mansour Ibraheem Mansour - 2 years ago 187
Javascript Question

Pass C# variable to JavaScript in ASP webforms

I'm using ASP web forms. Suppose I have a variable in my user control (ascx.cs)

protected void Page_Load(object sender, EventArgs e)
public string someText = "Hello World";

I want to pass this variable to JavaScript. The code in the ascx file:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CalendarUserControl.ascx.cs" Inherits="Fransabank.Calendar.CalendarUserControl" %>

<script type="text/javascript">

I'm getting in the console window:

ReferenceError: someText is not defined

Answer Source


My bad, I thought you've been using ASP.Net MVC. I've left the MVC solution below, but I'll also show you how can this be done with ASP.Net.

In Web Forms, you can add a property in your code-behind:

public string someText {get; set;}

And in front-end:

<script type="text/javascript">
    console.log('<%= someText %>');

MVC Solution

Passing values like that can be achieved, but is - in most cases - wrong. You should rather use a ViewModel - this is what MVC was created for.

Create a Model:

public class MyViewModel
    public string someText {get; set;}

When you return your View from Controller, use:

public ActionResult Index
    return View(new MyViewModel() { someText = "lalalala" });

Your View (cshtml):

@model(MyViewModel) // be sure to use whole namespace, like Models.MyViewModel

And in your js:

<script type="text/javascript">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download