我正在使用ASP Web表单。假设我的用户控件中有一个变量(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
编辑
不好,我以为您一直在使用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返回视图时,请使用:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句