jQuery 如何在脚本标签中获取模型或视图包变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18872720/
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
How to get to Model or Viewbag Variables in a Script Tag
提问by Don Thomas Boyle
Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First
Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First
Here is my very simple Script
这是我的很简单 Script
<script class="TractsScript">
$('#Add').click(function (e) {
var val = @ViewBag.ForSection;
alert(val);
});
</script>
As per example I am wanting to simply set a variable in my script
or USE a Viewbag.
or Model.
根据示例,我只想在 my script
or USE a Viewbag.
or 中设置一个变量Model.
I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer
我无法在以下任何论坛中找到答案:StckTrace1、StackTraceBetterAnswer
Other Things i have tried:
我尝试过的其他事情:
var model = @Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(@ViewBag.ForSection);
回答by Fals
You can do this way, providing Json or Any other variable:
您可以这样做,提供 Json 或任何其他变量:
1) For exemple, in the controller, you can use Json.NET
to provide Json
to the ViewBag
:
1)例如,在控制器中,您可以使用Json.NET
提供Json
给ViewBag
:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View
, put the script like this at the bottom of the page.
2) 在 中View
,将这样的脚本放在页面底部。
<script type="text/javascript">
var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
回答by James
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
你所拥有的应该工作。这取决于您设置的数据类型,即如果它是一个字符串值,您需要确保它在引号中,例如
var val = '@ViewBag.ForSection';
If it's an integer you need to parseit as one i.e.
如果它是一个整数,你需要将它解析为一个,即
var val = parseInt(@ViewBag.ForSection);
回答by Thas
try this method
试试这个方法
<script type="text/javascript">
function set(value) {
return value;
}
alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));
</script>
Thanks
谢谢
回答by esi
Use single quotation marks ('
):
使用单引号 ( '
):
var val = '@ViewBag.ForSection';
alert(val);
回答by Johan
When you're doing this
当你这样做时
var model = @Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
您可能得到的是 JSON 字符串,而不是 JavaScript 对象。
You need to parse it in to an object:
您需要将其解析为一个对象:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);