[英]How do I set Razor variabele in Javascript?
I'm setting Razor variables with data from my controller like this: 我正在使用来自控制器的数据设置Razor变量,如下所示:
@{
var filterData = ((ShipmentController)this.ViewContext.Controller).GetNoCmrs(new List<int>() { 1 });
}
I want to change this data based on the selected option the user selects (within a select). 我想根据用户选择的选项(在选择范围内)更改此数据。
<script>
var x;
function loadShipmentsByCondition() {
x = document.getElementById("conditionSelect").value;
if (x === "CMR not received") {
@filterData = @newData;
} else if(x === "Not invoiced") {
console.log("INVOICE");
@filterData = @otherData;
}
}
</script>
Is this possible? 这可能吗? Or if not, how can I do this efficiently? 否则,我该如何有效地做到这一点? I'm using MVC ASP.NET and vue js as front-end. 我正在使用MVC ASP.NET和vue js作为前端。
Thanks 谢谢
Unfortunately, you cannot get JavaScript to change a value of your backend C# code because JavaScript, once rendered on the frontend, does not know anything about your C# code on the server. 不幸的是,您无法使JavaScript更改后端C#代码的值,因为JavaScript一旦在前端呈现,就对服务器上的C#代码一无所知。
However, you can assign a C# value to a JavaScript variable before it leaves the server. 但是,您可以在JavaScript变量离开服务器之前为其分配C#值。 What this is doing is just injecting the value of @filterData into the html page in the script and then is assigned to the real JavaScript variable in the actual JS environment during runtime: 这样做只是将@filterData的值注入脚本中的html页面,然后在运行时在实际的JS环境中将其分配给实际的JavaScript变量:
<script>
var x;
var filterData = @filterData;
var otherData = @otherData;
var newData = @newData;
function loadShipmentsByCondition() {
x = document.getElementById("conditionSelect").value;
if (x === "CMR not received") {
filterData = newData;
} else if(x === "Not invoiced") {
console.log("INVOICE");
filterData = otherData;
}
}
</script>
So you are essentially converting those C# variables into JavaScript variables, but if you really need to change the C# variables then you would have to do a postback, or AJAX call to the server. 因此,您实际上是将这些C#变量转换为JavaScript变量,但是如果您确实需要更改C#变量,则必须对服务器执行回发或AJAX调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.