javascript 如何在asp.net MVC4中将模型从视图传递给javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19201970/
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 pass model from view to javascript in asp.net MVC4
提问by Alaa Shehebar
I'm new to asp.net MVC4, please be patient.
我是 ASP.NET MVC4 的新手,请耐心等待。
I have a controller which returns ActionResult with a model. I can use this model through Razor but I'd like to use it in JavaScript. this what I've tried to do according to some answers on the internet:
我有一个控制器,它返回带有模型的 ActionResult。我可以通过 Razor 使用这个模型,但我想在 JavaScript 中使用它。这是我根据互联网上的一些答案尝试做的:
@{
var property = Model;
}
var prop = @(property);
var data= @Html.Raw(Json.Encode(prop ));
But it's not working. What do I need to do in order to pass my model to JavaScript?
但它不起作用。我需要做什么才能将我的模型传递给 JavaScript?
回答by Satpal
Just use
只需使用
<script>
var data = @Html.Raw(Json.Encode(Model));
</script>
Problem with Your Code
你的代码有问题
@{
var property = Model;
}
var prop = @(property); //Here model is not properly encoded
var data= @Html.Raw(Json.Encode(prop )); //You are passing Javascript variable