将C#变量传递给ASP webforms中的JavaScript

时间:2016-05-06 10:24:13

标签: javascript c# webforms

我正在使用ASP网络表单。假设我的用户控件中有一个变量(ascx.cs)

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

我想将此变量传递给JavaScript。 ascx文件中的代码:

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

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

我进入控制台窗口:

  

ReferenceError:someText未定义

2 个答案:

答案 0 :(得分:0)

修改

我的不好,我以为你一直在使用ASP.Net MVC。我已经离开了MVC解决方案,但我也会告诉你如何用ASP.Net完成这项工作。

在Web窗体中,您可以在代码隐藏中添加属性:

public string someText {get; set;}

在前端:

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

MVC解决方案

传递这样的值可以实现,但在大多数情况下是错误的。您应该使用ViewModel - 这就是为MVC创建的。

创建模型:

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

从Controller返回View时,请使用:

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

您的观点(cshtml):

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

在你的js:

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

答案 1 :(得分:0)

您可以使用内联服务器标记:

public string SomeText
{
    get { return "sometext"; }
}

在你的标记中:

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

或者您可以使用HiddenField

protected void Page_Load(object sender, EventArgs e)
{
     hdnSomeText.value = "sometext";
}

标记:

<asp:HiddenField ID="hdnSomeText" runat="server" ClientIDMode="Static" />

<script type="text/javascript">
    console.log(document.getElementById('hdnSomeText').value);
</script>