[英]how to pass a value from javascript variable to c# variable in asp.net mvc
[英]Pass C# variable to JavaScript in ASP webforms
我正在使用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>
您可以使用內聯服務器標簽:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.