Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 17:37
    Jeff
    0

    How do I embed javascript code within razor?

    Hello:

    I have a foreach loop that I have some javascript in. It does not recognize the javascript and script, but as razor code. How do I denote that the chunk is javascript? 

                      @foreach(var contact in Model.inquiryContacts)
                      {
                        if(selectedOption == @contact.inquiry){
                           alert(@contact.inquiry);
                        }
                      }

    Any help would be much appreciated. 

    Thank you.

  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 17:42
    Jeff
    0

    The <text> tags doesn't seem to work in this case.

  • Grant Thomas 291 posts 324 karma points
    Apr 11, 2012 @ 17:51
    Grant Thomas
    0

    You could use @Html.Raw:

    var jsAlertFormat = "alert({0});";
    var jsAlert = string.Format(jsAlertFormat, contact.inquiry);
    @Html.Raw(jsAlert)

    I don't see, but trust that you are in, a <script> context.

  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 17:56
    Jeff
    0

    What about the if condition? Should I put that into a string too?

  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 17:57
    Jeff
    0

    Yes it is all inside <script> tags

  • Grant Thomas 291 posts 324 karma points
    Apr 11, 2012 @ 18:06
    Grant Thomas
    0

    No, your condition is part of your code, which isn't the problem - leave that as is and extend it with what I provided.

  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 18:15
    Jeff
    0

    aaagghhh it's not working

  • Jeff 21 posts 42 karma points
    Apr 11, 2012 @ 18:45
    Jeff
    1

    Got it !

     

                  @foreach(var contact in Model.inquiryContacts)
                  {
                    @Html.Raw"if(selectedOption == '" @contact.inquiry.InnerText "'){emailChangeTo = '" @contact.email.InnerText "';} \r\n" );
                  }

     

    For some reason, the String.Format wouldn't work....but yea...HTML.Raw is the way to go !!!! Thanks so much !!!!

  • Grant Thomas 291 posts 324 karma points
    Apr 11, 2012 @ 19:18
    Grant Thomas
    0

    Oh, I didn't realise the 'if' statement was supposed to be part of the JS, my apologies.

    Glad you got it sorted, good job.

Please Sign in or register to post replies

Write your reply to:

Draft