Reputation: 1648
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, 'D',
@((List<DateTime>)ViewBag.dates).ElementAt(0) ,
'#Sun1D');"
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
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
Reputation: 3634
@Html.CheckBox("Sun1D", new { onclick = "addRemEvent(1, 'D',"+
((List<DateTime>)ViewBag.dates).ElementAt(0)+" , '#Sun1D');"
, htmlAttributes = new { @class = "form-control" } })
Upvotes: 0