Blaze Mathew
Blaze Mathew

Reputation: 55

Escaping javascript in Razor

I am using razor to generate a javascript in razor loop however i am unable to use variable in it

This is my code

<script>
$(function () {

     @Html.Raw("$('#@Html.IdFor(m => m.DG['@i'].status_code)').on('change', function () { Dg_Calculate('@i');});")
     @Html.Raw("$('#@Html.IdFor(m => m.DG['@i'].belasting)').on('change', function () { Dg_Calculate('@i'); });")
     @Html.Raw("$('#@Html.IdFor(m => m.DG['@i'].max_belasting)').on('change', function () {Dg_Calculate('@i');});")

      $("#txtDate").datepicker();
 });

 function Dg_Calculate(item) {
 alert(item);
 }
</script>

Here in the generated code "@i" is coming as it is and not value of "i"

Upvotes: 0

Views: 69

Answers (2)

Ammar
Ammar

Reputation: 818

Your string that is passed to @Html.IdFor is treated as string, so using @ inside it means nothing.

You can alternatively use string interpolation, and your code should look something like:


<script>
    $(function () {
        @for (var i = 0; i < 15; i++) {
            @Html.Raw($"$('#{Html.IdFor(m => m.DG[i].status_code)}').on('change', function () {{ Dg_Calculate({i});}});")
            @Html.Raw($"$('#{Html.IdFor(m => m.DG[i].belasting)}').on('change', function () {{ Dg_Calculate({i});}});")
            @Html.Raw($"$('#{Html.IdFor(m => m.DG[i].max_belasting)}').on('change', function () {{ Dg_Calculate({i});}});")
        }

        $("#txtDate").datepicker();
    });

    function Dg_Calculate(item) {
        alert(item);
    }
</script>

Upvotes: 1

Matt Stannett
Matt Stannett

Reputation: 2728

I think I understand what you are trying to achieve - whenever any of the 14 elements that has the following classes status_code, belasting, max_belasting you want to call the Dg1_Calculate function.

If this is the case then this is more easily achieved in Javascript itself rather than trying to write Razor code to generate Javascript. It looks like you're using jQuery syntax so how about something like this:

@section Scripts {
    <script type="text/javascript">
        $('.status_code,.belasting,.max_belasting').on('change', function()
        {
             var index = $('.status_code,.belasting,.max_belasting').index(this);
             Dg_Calculate(index);
        });

       function Dg_Calculate(index) {
          console.log(index)
       }
    </script>
}

You will probably also need to include the jQuery library above your script section/in your layout template if it is not already done, something like:

@Scripts.Render("~/bundles/jquery")

For reference see the Javascript Libraries section, and jQuery multiple selector.

Upvotes: 0

Related Questions