在 javascript 中设置剃刀变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6500941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting razor variables in javascript
提问by TomDW
I am trying to assign a razor variable with the contents of a combo box on my form from within a javascript function. Like so:
我正在尝试从 javascript 函数中为表单上的组合框的内容分配一个 razor 变量。像这样:
<script type ="text/javascript">
<!--
function SomeFunction() {
var hours = document.getElementById("Hours");
var task = document.getElementById("TaskType_ID");
@{
var tsk = @:task.value;
}
@{
<text>
hours.value = '@ViewBag.TaskTypes.GetHours(tsk)';
</text>
}
return true;
}
//-->
</script>
the line (and every other variation I've tried)
线路(以及我尝试过的所有其他变体)
var tsk = @:task.value;
results in an error.
导致错误。
采纳答案by Xnake
As Chris pointed out, you are mixing the client and server code. The javascript is the client code, and you need the data from the server to return the value you want by using ajax calling function(get/post). Here is the snippet code of what you can do about it:
正如 Chris 指出的那样,您正在混合客户端和服务器代码。javascript是客户端代码,你需要来自服务器的数据通过ajax调用函数(get/post)返回你想要的值。以下是您可以对其采取的措施的片段代码:
$("#tasks").change(function(){
$.get('url',$(this).val(), function(data){
// data is the hours returned from the selected task
$("#hours").val(data);
});
});
Or instead of making calls to the server everytime you select a task, you can always store the values of the tasks in a variable. Thanks
或者,您可以始终将任务的值存储在变量中,而不是每次选择任务时都调用服务器。谢谢
回答by TomDW
okay. here's what i wound up doing. I no longer pass in an object into the view. I added a script that binds to the change event of my first field, and then called an action in my controller via ajax and puts the result into the second field. Like so:
好的。这就是我最终要做的。我不再将对象传递到视图中。我添加了一个脚本,绑定到我的第一个字段的更改事件,然后通过 ajax 在我的控制器中调用一个操作并将结果放入第二个字段。像这样:
<script type="text/javascript">
$(document).ready(function () {
$("#q").change(function () {
$.ajax({
type: "GET",
url: "Home/Test?value=" + $('#q').get(0).value,
success: function(msg) {
$('#x').get(0).value = msg;
}
});
});
});
</script>
thank you for leading me in the right direction. With all of the razor syntax, I lost sight of the hact that this is still html. I hope you all enjoyed watching me attempt to pound a square peg into a round hole!
谢谢你带领我走向正确的方向。使用所有 razor 语法,我忽略了这仍然是 html 的特性。我希望你们都喜欢看我尝试将方钉敲入圆孔的过程!