简体   繁体   English

ASP.NET MVC 5-@ C#代码在运行时未翻译

[英]ASP.NET MVC 5 - @C# code not being translated at runtime

So I'm trying to dynamically pass some data to a javascript function to update some UI for the user. 因此,我试图将一些数据动态传递给javascript函数以为用户更新一些UI。

 @Html.CheckBox("Sun1D", new { onclick = "addRemEvent(1, 'D', 
                   @((List<DateTime>)ViewBag.dates).ElementAt(0) , '#Sun1D');"
                  , htmlAttributes = new { @class = "form-control" } })

However at runtime, the code doesn't seem to get translated and I end up with 但是在运行时,代码似乎没有得到翻译,我最终得到了

<input htmlAttributes="{ class = form-control }" 
 id="Sun1D" 
 name="Sun1D" 
 onclick="addRemEvent(1, &#39;D&#39;,
 @((List&lt;DateTime>)ViewBag.dates).ElementAt(0) , 
 &#39;#Sun1D&#39;);" 
 type="checkbox" value="true" />

Now you can see the problem here. 现在您可以在这里看到问题了。 There should be a date value in that javascript function call, but I'm just getting my C# code as a literal. 该javascript函数调用中应该有一个日期值,但我只是将C#代码作为文字。

You're sending server-side code to the client as a string. 您正在将服务器端代码作为字符串发送到客户端。 It's not going to execute that string, it's just going to send it to the client. 它不会执行该字符串,而只是将其发送给客户端。

To simplify, instead of something like this: 为了简化,而不是像这样:

new { onclick="some text @someCode more text" }

you'd want this: 您想要这个:

new { onclick="some text " + someCode + " more text" }

In yours that might look something like: 在您看来,可能类似于:

new { onclick = "addRemEvent(1, 'D', " + ((List<DateTime>)ViewBag.dates).ElementAt(0) + " , '#Sun1D');" }

There's nothing special about the fact that it's Razor syntax, code is still code. 它是Razor语法,代码仍然是代码,这没有什么特别的。 You're writing C# code to build a string to put in the onclick property of an object. 您正在编写C#代码以构建要放入对象的onclick属性的字符串。 You'd build that string just like you build any other string in C#. 您将像在C#中构建任何其他字符串一样构建该字符串。 (Which means you could also make use of string.Format() , etc. if you like.) (这意味着您也可以根据需要使用string.Format()等。)

@Html.CheckBox("Sun1D", new { onclick = "addRemEvent(1, 'D',"+ 
                   ((List<DateTime>)ViewBag.dates).ElementAt(0)+" , '#Sun1D');"
                  , htmlAttributes = new { @class = "form-control" } })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM