C# 可以从 Javascript 文件访问 MVC ViewBag 对象吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10389649/
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
Possible to access MVC ViewBag object from Javascript file?
提问by Abe Miessler
Is it possible to do the following from a javascript file in an MVC application?
是否可以从 MVC 应用程序中的 javascript 文件执行以下操作?
$(function(){
alert(@ViewBag.someValue);
}
Currently it throws the error:
目前它抛出错误:
reference to undefined XML name @ViewBag
对未定义 XML 名称 @ViewBag 的引用
采纳答案by Ethan Brown
I don't believe there's currently any way to do this. The Razor engine does not parse Javascript files, only Razor views. However, you can accomplish what you want by setting the variables inside your Razor view:
我不相信目前有任何方法可以做到这一点。Razor 引擎不解析 Javascript 文件,只解析 Razor 视图。但是,您可以通过在 Razor 视图中设置变量来完成您想要的操作:
<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>
As Joe points out in the comments, the string value above will break if there's a single quote in it. If you want to make this completely iron-clad, you'll have to replace all single quotes with escaped single quotes. The problem there is that all of the sudden slashes become an issue. For example, if your string is "foo \' bar", and you replace the single quote, what will come out is "foo \\' bar", and you're right back to the same problem. (This is the age old difficulty of chained encoding.) The best way to handle this is to treat backslashes and quotes as special and make sure they're allescaped:
正如 Joe 在评论中指出的那样,如果上面有单引号,上面的字符串值就会中断。如果你想让这个完全铁定,你必须用转义的单引号替换所有单引号。问题是所有突然的斜线都成为一个问题。例如,如果您的字符串是“ foo \' bar”,而您替换了单引号,则会出现“ foo \\' bar”,而您又回到了同样的问题。(这是链式编码的古老难题。)处理这个问题的最佳方法是将反斜杠和引号视为特殊的,并确保它们都被转义:
@{
var safeStringValue = ViewBag.someStringValue
.Replace("\", "\\")
.Replace("'", "\'");
}
var someStringValue = '@(safeStringValue)';
回答by mattytommo
Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass ViewBagvalues in the class constructor.
不在 JavaScript 文件中,不。
您的 JavaScript 文件可能包含一个类,您可以在视图中实例化该类的新实例,然后您可以ViewBag在类构造函数中传递值。
Or if it's not a class, your only other alternative, is to use dataattributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.
或者,如果它不是类,那么您唯一的另一种选择是data在 HTML 元素中使用属性,将它们分配给视图中的属性并在 JS 文件中检索它们。
Assuming you had this input:
假设你有这个输入:
<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />
Then in your JS file you could get it by using:
然后在您的 JS 文件中,您可以使用以下方法获取它:
var myVal = $("#myInput").data("myValue");
回答by David
In order to do this your JavaScript file would need to be pre-processed on the server side. Essentially, it would have to becomean ASP.NET View of some kind, and scripttags which reference the file would essentially be referencing a controller action which responds with that view.
为此,您的 JavaScript 文件需要在服务器端进行预处理。从本质上讲,它必须成为某种类型的 ASP.NET 视图,并且script引用该文件的标签本质上将引用以该视图响应的控制器操作。
That sounds like a can of worms you don't want to open.
这听起来像是一罐你不想打开的蠕虫。
Since JavaScript is client-side, why not just set the value to some client-side element and have the JavaScript interact with that. It's perhaps an additional step of indirection, but it sounds like much less of a headache than creating a JavaScript view.
由于 JavaScript 是客户端,为什么不直接将值设置为某个客户端元素并让 JavaScript 与之交互。这可能是一个额外的间接步骤,但听起来不像创建 JavaScript 视图那么令人头疼。
Something like this:
像这样的东西:
<script type="text/javascript">
var someValue = @ViewBag.someValue
</script>
Then the external JavaScript file can reference the someValueJavaScript variable within the scope of that document.
然后外部 JavaScript 文件可以引用该someValue文档范围内的 JavaScript 变量。
Or even:
甚至:
<input type="hidden" id="someValue" value="@ViewBag.someValue" />
Then you can access that hidden input.
然后您可以访问该隐藏输入。
Unless you come up with some really slick way to actually make your JavaScript file usable as a view. It's certainly doable, and I can't readilythink of any problems you'd have (other than really ugly view code since the view engine will get veryconfused as to what's JavaScript and what's Razor... so expect a tonof <text>markup), so if you find a slick way to do it that would be pretty cool, albeit perhaps unintuitive to someone who needs to support the code later.
除非您想出一些非常巧妙的方法来实际使您的 JavaScript 文件可用作视图。这当然是可行的,而且我无法轻易想到您遇到的任何问题(除了非常丑陋的视图代码,因为视图引擎会对什么是 JavaScript 和什么是 Razor 感到非常困惑……所以期待大量的<text>标记) ,所以如果你找到一种巧妙的方法来做到这一点会很酷,尽管对于稍后需要支持代码的人来说可能不直观。
回答by aslanpayi
in Html:
在 HTML 中:
<input type="hidden" id="customInput" data-value = "@ViewBag.CustomValue" />
in Script:
在脚本中:
var customVal = $("#customInput").data("value");
回答by OAK
Create a view and return it as a partial view:
创建一个视图并将其作为局部视图返回:
public class AssetsController : Controller
{
protected void SetMIME(string mimeType)
{
this.Response.AddHeader("Content-Type", mimeType);
this.Response.ContentType = mimeType;
}
// this will render a view as a Javascript file
public ActionResult GlobalJS()
{
this.SetMIME("text/javascript");
return PartialView();
}
}
Then in the GlobalJS view add the javascript code like (adding the // will make visual studio intellisense read it as java-script)
然后在 GlobalJS 视图中添加 javascript 代码,如(添加 // 将使 Visual Studio Intellisense 将其读取为 java-script)
//<script>
$(document).ready(function () {
alert('@ViewBag.PropertyName');
});
//</script>
Then in your final view you can add a reference to the javascript just like this.
然后在您的最终视图中,您可以像这样添加对 javascript 的引用。
<script src="@Url.Action("GlobalJS", "Assets")"></script>
Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.
然后在您的最终视图控制器中,您可以创建/传递您的 ViewBags,它将在您的 javascript 中呈现。
public class MyFinalViewController : Controller
{
public ActionResult Index()
{
ViewBag.PropertyName = "My ViewBag value!";
return View();
}
}
Hope it helps.
希望能帮助到你。
回答by JSideris
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
我注意到如果你尝试这样做,Visual Studio 的内置错误检测器会变得愚蠢:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
因为@(ViewBag.someNumericValue) 有可能计算为空,这会导致生成以下错误的 JavaScript:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
如果您确定 someNemericValue 将设置为有效的数字数据类型,则可以通过执行以下操作来避免出现 Visual Studio 警告:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
这可能会生成以下示例:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
它适用于负数。如果该项目不在您的查看包中,Number() 的计算结果为 0。
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
不再有 Visual Studio 警告!但请确保该值已设置并且是数字,否则您将打开可能的 JavaScript 注入攻击或运行时错误的大门。
回答by Savita
In controllers action add:
在控制器动作中添加:
public ActionResult Index()
{
try
{
int a, b, c;
a = 2; b = 2;
c = a / b;
ViewBag.ShowMessage = false;
}
catch (Exception e)
{
ViewBag.ShowMessage = true;
ViewBag.data = e.Message.ToString();
}
return View(); // return View();
}
in Index.cshtml
Place at the bottom:
<input type="hidden" value="@ViewBag.data" id="hdnFlag" />
@if (ViewBag.ShowMessage)
{
<script type="text/javascript">
var h1 = document.getElementById('hdnFlag');
alert(h1.value);
</script>
<div class="message-box">Some Message here</div>
}
回答by Atiq Baqi
Use this code in your .cshtml file.
在您的 .cshtml 文件中使用此代码。
@{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var val = jss.Serialize(ViewBag.somevalue);
}
<script>
$(function () {
var val = '@Html.Raw(val)';
var obj = $.parseJSON(val);
console.log(0bj);
});
</script>

