Scuba Steve
Scuba Steve

Reputation: 1648

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.

 @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.

Upvotes: 0

Views: 70

Answers (2)

David
David

Reputation: 219016

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. You're writing C# code to build a string to put in the onclick property of an object. You'd build that string just like you build any other string in C#. (Which means you could also make use of string.Format(), etc. if you like.)

Upvotes: 3

levent
levent

Reputation: 3634

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

Upvotes: 0

Related Questions