简体   繁体   English

用C#代码编写JavaScript脚本

[英]Writing JavaScript script inside C# code

I have an asp.net application and i need to combine C# and javascript code: 我有一个asp.net应用程序,我需要结合C#和javascript代码:

<td >
    <label name="tag@(i)">@Model[1][i]._tag</label>
</td>
<td>
    <input type="text" value="@Model[1][i]._client" name="client@(i)"/>
</td>
<td>
    <input type="text" value="@Model[1][i]._reception"  class="datepicker" name="reception@(i)"/>
</td>
<td>
    <input type="text" value="@Model[1][i]._cloture"  class="datepicker" name="cloture@(i)"/>
</td>
<td>
    @{
        List<Planning.Models.Impaire> liste = u.Get_Impaire_List();
        Planning.Models.Impaire imp = liste.Find(x => x.id_paire == Model[1][i].Id);

        @{
            string reception =  @: <script>
            @: var f1 = $('input[name="reception' + @i.ToString() + '"]').val();
            @: document.write(f1);
            @: </script>
            ;
            string cloture =  @: <script>
            @: var f2 = $('input[name="cloture' + @i.ToString() + '"]').val();
            @: document.write(f2);
            @: </script>
            ;
            string client =  @: <script>
            @: var f3=  $('input[name="client' + @i.ToString() + '"]').val();
            @: document.write(f3);
            @: </script>
            ;
            string tag =  @: <script>
            @:var f4= $('input[name="tag' + @i.ToString() + '"]').val();
            @: document.write(f4);
            @: </script>
            ;
        }

        @Html.ActionLink("enregistrer","Index", new {identificateur = Model[1][i].Id, Pages = "1", _reception =reception, _cloture = cloture, _client = client, _tag = tag  })
    </td>  

But I have an exception in this line : @: var f1 = $('input[name="reception' + @i.ToString() + '"]').val(); 但是我在这一行有一个例外: @: var f1 = $('input[name="reception' + @i.ToString() + '"]').val(); 错误

What are the reasons of this error? 此错误的原因是什么? How can I fix it? 我该如何解决?

Having js inside the view like your sample is highly unlucky and can always be avoided. 像您的样本一样在视图内包含js是非常不幸的,可以始终避免。 Find a way to separate javascript from razor code as good as you can. 找到一种将javascript与razor代码尽可能分开的方法。 You could leave javascript variables inside the view alike 您可以在视图内保留javascript变量

var arr = [@i.ToString()]

and then, in a separate js file you process this js variable arr. 然后在一个单独的js文件中处理此js变量arr。

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

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