I want to call a JavaScript function in c# code in asp.net mvc3 view, but don\'t know how to do this. My code is following
Javascript Function
Well you can use something like this:
foreach (var item in collection) {
<script type="text/javascript">
JK();
</script>
}
If you need to use foreach inside the javascript code, you should just use . Like this:
<script type="text/javascript">
@foreach (var item in collection) {
<text>JK();</text>
}
</script>
You can't call JS function on server side only in the views. And it wiil look like
@foreach(var item in collection)
{
...
<script type="text/javascript">
JK()
</script>
...
}
Output html will contain several calls of this js function.
To call a javascript function
//C# Code
@Html.Raw("CallFunction('" + @param + "');");
//C# code..
Now for Javascript function
<script type="text/javascript">
CallFunction(param)
{
alert(param);
}
</script>
I would implement it little bit differently
@foreach(var item in collection)
{
<!-- some html element that will be generated on each loop cycle
<input type="hidden" class="item"/>
}
then with/without help of 3rd party JavaScript libraries
$(document).ready(function () {
$('.item').each(function () {
JK();
}
});