简体   繁体   中英

asp.net razor special character issue in javascript variable

I'm using razor in webmatrix and I have a problem with the string special character. I want to put a string into a varibale in the javascript but when I try to use the tag @ it shows a problem this is the code :

<script>
 $Edit.click(function() {
        var userid = $(this).closest('td').prev('td').text();
     var stringDiv = "@{ var selectQueryString4 =  SELECT * FROM DemandeConge where UserId = '\"+ trim(userid) + \"'\"+\";<h3>modifier la demande de congé de \" + userid +  \"</h3>foreach(var row in db.Query(selectQueryString4)){<form action='responsable.cshtml' method=\"post\"><label for=\"txtDebut\">Date début :</label><input type=\"text\" id=\"txtDebut\" value=\"+ @row.DateDebutDemande +\"/></br><label for=\"txtFin\">Date de fin :</label><input type=\"text\" id=\"txtFin\" value=\"+ @row.DateFinDemande +\"/></br> <label for=\"txtTypeCong\">Type de congé :</label><input type=\"text\" id=\"txtTypeCong\" value=\"+ @row.TypeConge +\"/><input type=\"hidden\" name=\"UserId\" value=\"+ @row.UserId +\" /><input type=\"hidden\" name=\"type\" value=\"edite\" /><input type=\"submit\" value=\"Oui\"  /> <input type=\"button\" value=\"No\" onclick=\"$('#edite').slideUp(); document.getElementById('edite').innerHTML = ' '\" /> </form>}}}");


    document.getElementById('edite').innerHTML = stringDiv ;
        $('#edite').slideDown(1000);

        )
</script>

So I want to know if there is any way to solve this problem.

使用double @ like @@而不是@@

Based on your error , you must be using ' ' (simple quotes ) somewhere and it get compiled by the razor engine. try to change all your ' in \\" in your "" strings.

try for yourself , if you declare a string like this 'aa' you will get the same error in Csharp ,because you have to use "aa" to declare a string literal. '' are for character literals.

anyway in my opinion you should not mix js and C#. if you need to pass variables from C# to Js use either ajax ,or another solution like hidden input fields. or create templates like that :

<script type='text/template' id='mytemplate'>
<div>@myVar</div>
</script>

and get the content of the template with

$templateContent= $("#mytemplate").html()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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